/* global React */
// Organization Settings — modal-style page with two cards:
//   1. Company info — large textarea (everything about the company)
//   2. Knowledge base — drag/drop upload (pdf, doc, docx, md, pptx) + preview

const { useState: useOS, useEffect: useOE, useRef: useOR, useMemo: useOM } = React;

const ALLOWED = {
  pdf:  { mime: 'application/pdf',                                                              label: 'PDF',  color: '#C65A42' },
  doc:  { mime: 'application/msword',                                                            label: 'DOC',  color: '#2A5599' },
  docx: { mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',       label: 'DOCX', color: '#2A5599' },
  md:   { mime: 'text/markdown',                                                                 label: 'MD',   color: '#3F4A28' },
  pptx: { mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',     label: 'PPTX', color: '#B7791F' },
};
const ALLOWED_EXTS = Object.keys(ALLOWED);
const ALLOWED_ACCEPT = ALLOWED_EXTS.map(e => '.' + e).join(',');

function fmtBytes(n) {
  if (n == null || isNaN(n)) return '—';
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
function fmtDate(iso) {
  if (!iso) return '—';
  try {
    const d = new Date(iso);
    return d.toLocaleString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
  } catch { return iso; }
}
function extFromName(name) {
  const m = String(name || '').toLowerCase().match(/\.([a-z0-9]+)$/);
  return m ? m[1] : '';
}

// Reads the JWT the auth flow stores in localStorage so /api/orgs/:id/settings
// (which requireAuths) accepts our requests. Returns an empty object when
// nothing is stored so the caller can spread it unconditionally.
function osAuthHeaders() {
  let token = null;
  try { token = localStorage.getItem('pr.token'); } catch {}
  return token ? { Authorization: `Bearer ${token}` } : {};
}

function OrgSettings({ orgId, orgName, onClose, onSaved, orgPicker }) {
  // orgPicker (super-admin only): { orgs: [{id,name}], onChange: (newId) => void }
  // When provided, the header renders a dropdown to switch between orgs in place.
  const [info, setInfo] = useOS('');
  const [files, setFiles] = useOS([]);
  const [brand, setBrand] = useOS([]);
  const [loading, setLoading] = useOS(true);
  const [savingInfo, setSavingInfo] = useOS(false);
  const [savedFlash, setSavedFlash] = useOS(false);
  const [error, setError] = useOS('');
  const [dragOver, setDragOver] = useOS(false);
  const [uploading, setUploading] = useOS(false);
  const [brandDragOver, setBrandDragOver] = useOS(false);
  const [brandUploading, setBrandUploading] = useOS(false);
  const [brandPreview, setBrandPreview] = useOS(null);
  const [activeFile, setActiveFile] = useOS(null);
  const [activePreview, setActivePreview] = useOS({ url: null, kind: null, error: null });
  const fileInputRef = useOR(null);
  const brandInputRef = useOR(null);

  // Initial load
  useOE(() => {
    let cancelled = false;
    (async () => {
      try {
        const r = await fetch(`/api/orgs/${encodeURIComponent(orgId)}/settings`, {
          headers: { ...osAuthHeaders() },
        });
        const d = await r.json().catch(() => ({}));
        if (cancelled) return;
        setInfo(d?.settings?.info || '');
        setFiles(d?.settings?.files || []);
        setBrand(d?.settings?.brand || []);
      } catch (e) {
        if (!cancelled) setError(String(e?.message || e));
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [orgId]);

  // Auto-select first file for preview when files change
  useOE(() => {
    if (!activeFile && files.length) setActiveFile(files[0]);
    if (activeFile && !files.find(f => f.id === activeFile.id)) {
      setActiveFile(files[0] || null);
    }
  }, [files]);

  // Build preview when activeFile changes
  useOE(() => {
    setActivePreview({ url: null, kind: null, error: null });
    if (!activeFile) return;
    const ext = activeFile.ext || extFromName(activeFile.name);
    if (!activeFile.dataUrl) {
      setActivePreview({ url: null, kind: ext, error: 'No preview available — file content was not stored.' });
      return;
    }
    if (ext === 'pdf') {
      setActivePreview({ url: activeFile.dataUrl, kind: 'pdf', error: null });
    } else if (ext === 'md') {
      // Decode the data URL → text
      try {
        const b64 = activeFile.dataUrl.split(',', 2)[1] || '';
        const text = decodeURIComponent(escape(atob(b64)));
        setActivePreview({ url: text, kind: 'md', error: null });
      } catch (e) {
        setActivePreview({ url: null, kind: 'md', error: 'Could not decode markdown.' });
      }
    } else {
      // doc/docx/pptx — no in-browser preview, show metadata + download
      setActivePreview({ url: activeFile.dataUrl, kind: ext, error: null });
    }
  }, [activeFile && activeFile.id]);

  // Saves company_info and returns whether the save succeeded. Used by the
  // Done button so we only close on success.
  const saveInfo = async () => {
    setSavingInfo(true); setError('');
    try {
      const r = await fetch(`/api/orgs/${encodeURIComponent(orgId)}/settings`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...osAuthHeaders() },
        body: JSON.stringify({ info }),
      });
      if (!r.ok) {
        const d = await r.json().catch(() => ({}));
        throw new Error(d.error || `Save failed (${r.status})`);
      }
      onSaved && onSaved();
      return true;
    } catch (e) {
      setError(String(e?.message || e));
      return false;
    } finally {
      setSavingInfo(false);
    }
  };

  // Done = save pending edits (company info — KB/brand-kit upload inline as
  // they're chosen) then close. We block close on save failure so the user
  // sees the error and doesn't lose their typed info.
  const handleDone = async () => {
    if (savingInfo || uploading || brandUploading) return;
    const ok = await saveInfo();
    if (ok) onClose();
  };

  const handleFiles = async (fileList) => {
    setError('');
    if (!fileList || !fileList.length) return;
    const list = Array.from(fileList);
    setUploading(true);
    try {
      for (const f of list) {
        const ext = extFromName(f.name);
        if (!ALLOWED_EXTS.includes(ext)) {
          setError(`Unsupported type: ${f.name}. Allowed: ${ALLOWED_EXTS.join(', ').toUpperCase()}.`);
          continue;
        }
        // Cap at ~6MB to avoid blowing localStorage. Real backend would stream.
        if (f.size > 6 * 1024 * 1024) {
          setError(`${f.name} is too large for the preview (>6 MB). Use a smaller file.`);
          continue;
        }
        const dataUrl = await new Promise((res, rej) => {
          const r = new FileReader();
          r.onload = () => res(r.result);
          r.onerror = rej;
          r.readAsDataURL(f);
        });
        const r = await fetch(`/api/orgs/${encodeURIComponent(orgId)}/knowledge-base`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', ...osAuthHeaders() },
          body: JSON.stringify({
            name: f.name,
            size: f.size,
            type: f.type || ALLOWED[ext]?.mime || '',
            ext,
            dataUrl,
          }),
        });
        const d = await r.json().catch(() => ({}));
        if (r.ok && d.settings) {
          setFiles(d.settings.files || []);
          setActiveFile(d.file);
        }
      }
    } catch (e) {
      setError(String(e?.message || e));
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const removeFile = async (fileId) => {
    try {
      const r = await fetch(`/api/orgs/${encodeURIComponent(orgId)}/knowledge-base?fileId=${encodeURIComponent(fileId)}`, {
        method: 'DELETE',
        headers: { ...osAuthHeaders() },
      });
      const d = await r.json().catch(() => ({}));
      if (r.ok && d.settings) setFiles(d.settings.files || []);
    } catch (e) {
      setError(String(e?.message || e));
    }
  };

  // ----- Brand kit -----
  // Brand kit accepts anything: logos, document templates, fonts, colors, images.
  // We classify by extension to render the right thumbnail.
  const BRAND_KIND = (ext) => {
    const e = (ext || '').toLowerCase();
    if (['svg', 'png', 'jpg', 'jpeg', 'webp', 'gif'].includes(e)) return 'image';
    if (['ttf', 'otf', 'woff', 'woff2'].includes(e)) return 'font';
    if (['ai', 'eps', 'sketch', 'fig', 'xd'].includes(e)) return 'design';
    if (['pdf'].includes(e)) return 'doc';
    if (['doc', 'docx', 'pptx', 'ppt', 'key', 'xlsx'].includes(e)) return 'template';
    return 'other';
  };

  const handleBrandFiles = async (fileList) => {
    setError('');
    if (!fileList || !fileList.length) return;
    const list = Array.from(fileList);
    setBrandUploading(true);
    try {
      for (const f of list) {
        // Cap at ~6MB to avoid blowing localStorage. Real backend would stream.
        if (f.size > 6 * 1024 * 1024) {
          setError(`${f.name} is too large for the preview (>6 MB).`);
          continue;
        }
        const ext = extFromName(f.name);
        const dataUrl = await new Promise((res, rej) => {
          const r = new FileReader();
          r.onload = () => res(r.result);
          r.onerror = rej;
          r.readAsDataURL(f);
        });
        const r = await fetch(`/api/orgs/${encodeURIComponent(orgId)}/brand-kit`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', ...osAuthHeaders() },
          body: JSON.stringify({
            name: f.name, size: f.size, type: f.type || '', ext,
            kind: BRAND_KIND(ext), dataUrl,
          }),
        });
        const d = await r.json().catch(() => ({}));
        if (r.ok && d.settings) setBrand(d.settings.brand || []);
      }
    } catch (e) {
      setError(String(e?.message || e));
    } finally {
      setBrandUploading(false);
      if (brandInputRef.current) brandInputRef.current.value = '';
    }
  };

  const removeBrand = async (fileId) => {
    try {
      const r = await fetch(`/api/orgs/${encodeURIComponent(orgId)}/brand-kit?fileId=${encodeURIComponent(fileId)}`, {
        method: 'DELETE',
        headers: { ...osAuthHeaders() },
      });
      const d = await r.json().catch(() => ({}));
      if (r.ok && d.settings) setBrand(d.settings.brand || []);
    } catch (e) {
      setError(String(e?.message || e));
    }
  };

  const downloadBrand = (f) => {
    if (!f || !f.dataUrl) return;
    const a = document.createElement('a');
    a.href = f.dataUrl;
    a.download = f.name || 'brand-asset';
    document.body.appendChild(a);
    a.click();
    a.remove();
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(23,53,64,0.36)',
      zIndex: 220, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, animation: 'pr-fade-in .15s ease-out',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 1120, maxWidth: '100%', maxHeight: '92vh',
        background: 'var(--c-cream-50)', border: '1px solid var(--border-subtle)',
        borderRadius: 18, boxShadow: 'var(--shadow-float-lg)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        {/* Header */}
        <header style={{
          display: 'flex', alignItems: 'flex-start', gap: 14,
          padding: '20px 24px 18px', borderBottom: '1px solid var(--border-subtle)',
          background: 'var(--c-cream-100)', flex: 'none',
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12, flex: 'none',
            background: 'var(--c-petrol-800)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <img src="../assets/icons/settings.svg" width={20} height={20} alt=""
              style={{ filter: 'invert(1) brightness(2)' }} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="eyebrow" style={{ color: 'var(--c-ink-500)', letterSpacing: '1.5px' }}>Organization</div>
            {orgPicker && Array.isArray(orgPicker.orgs) ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 4, flexWrap: 'wrap' }}>
                <select
                  value={orgId}
                  onChange={(e) => orgPicker.onChange && orgPicker.onChange(e.target.value)}
                  style={{
                    fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 700, fontSize: 20,
                    letterSpacing: '-0.02em', color: 'var(--c-ink-800)',
                    background: 'var(--c-white)', border: '1.5px solid var(--border-subtle)',
                    borderRadius: 10, padding: '6px 32px 6px 12px',
                    boxShadow: 'var(--shadow-raised-sm)', cursor: 'pointer', maxWidth: 360,
                    appearance: 'none', WebkitAppearance: 'none',
                    backgroundImage: 'linear-gradient(45deg, transparent 50%, var(--c-ink-600) 50%), linear-gradient(135deg, var(--c-ink-600) 50%, transparent 50%)',
                    backgroundPosition: 'calc(100% - 16px) 55%, calc(100% - 11px) 55%',
                    backgroundSize: '5px 5px, 5px 5px',
                    backgroundRepeat: 'no-repeat',
                  }}
                >
                  {orgPicker.orgs.map(o => (
                    <option key={o.id} value={o.id}>{o.name}</option>
                  ))}
                </select>
                <span style={{ fontSize: 11, color: 'var(--c-ink-500)' }}>Super admin · pick organization</span>
              </div>
            ) : (
              <div style={{
                fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 700, fontSize: 22,
                letterSpacing: '-0.02em', color: 'var(--c-ink-800)', marginTop: 4,
              }}>{orgName || 'Company'} settings</div>
            )}
            <div style={{ fontSize: 12, color: 'var(--c-ink-600)', marginTop: 4 }}>
              Company info and knowledge base. Visible only to admins.
            </div>
          </div>
          <button onClick={onClose} title="Close" style={{
            width: 36, height: 36, borderRadius: 10, border: '1px solid var(--border-subtle)',
            background: 'var(--c-white)', boxShadow: 'var(--shadow-raised-sm)', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none',
          }}>
            <img src="../assets/icons/cross.svg" width={12} height={12} alt="Close" />
          </button>
        </header>

        {/* Body */}
        <div style={{ flex: 1, overflow: 'auto', padding: '22px 24px', display: 'flex', flexDirection: 'column', gap: 22 }}>
          {error && (
            <div style={{
              padding: '10px 14px', borderRadius: 10,
              background: 'var(--c-terra-100, #FBE7E0)',
              border: '1px solid var(--c-terra-600, #C65A42)',
              color: 'var(--c-terra-600, #C65A42)',
              fontSize: 13,
            }}>{error}</div>
          )}

          {/* Company info card */}
          <section style={cardStyle}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
              <h2 style={cardTitleStyle}>Company info</h2>
              <span style={{ fontSize: 12, color: 'var(--c-ink-500)' }}>
                Everything about the company — used to ground every conversation.
              </span>
            </div>
            <textarea
              value={info}
              onChange={e => setInfo(e.target.value)}
              placeholder={`Mission, products, audience, voice, key terminology, escalation paths, anything else worth telling the model up front…`}
              spellCheck={true}
              style={{
                width: '100%', minHeight: 180, padding: 14, borderRadius: 12,
                background: 'var(--c-cream-50)',
                border: '1.5px solid var(--border-subtle)',
                boxShadow: 'var(--shadow-inset-input)',
                fontFamily: "'Suisse Int\\'l', sans-serif", fontSize: 14, lineHeight: 1.55,
                color: 'var(--c-ink-900)', outline: 'none', resize: 'vertical', boxSizing: 'border-box',
              }}
            />
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10 }}>
              <span style={{ fontSize: 11, color: 'var(--c-ink-500)' }}>
                {info.length.toLocaleString()} characters
              </span>
              <div style={{ flex: 1 }} />
              <span style={{ fontSize: 11, color: 'var(--c-ink-500)' }}>
                Click <strong style={{ color: 'var(--c-ink-700)' }}>Done</strong> to save.
              </span>
            </div>
          </section>

          {/* Knowledge base card */}
          <section style={cardStyle}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
              <h2 style={cardTitleStyle}>Knowledge base</h2>
              <span style={{ fontSize: 12, color: 'var(--c-ink-500)' }}>
                {files.length} {files.length === 1 ? 'document' : 'documents'} · accepts {ALLOWED_EXTS.join(', ').toUpperCase()}
              </span>
            </div>

            {/* Drop zone */}
            <div
              onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
              onDragLeave={() => setDragOver(false)}
              onDrop={(e) => {
                e.preventDefault();
                setDragOver(false);
                handleFiles(e.dataTransfer.files);
              }}
              onClick={() => fileInputRef.current?.click()}
              style={{
                border: `2px dashed ${dragOver ? 'var(--c-petrol-500)' : 'var(--c-cream-300)'}`,
                background: dragOver ? 'var(--c-petrol-050)' : 'var(--c-cream-50)',
                borderRadius: 14, padding: '22px 18px',
                display: 'flex', alignItems: 'center', gap: 14,
                cursor: 'pointer', transition: 'all .15s ease-out',
              }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12, flex: 'none',
                background: 'var(--c-petrol-050)', color: 'var(--c-petrol-800)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <img src="../assets/icons/plus.svg" width={18} height={18} alt="" />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 500, fontSize: 14,
                  color: 'var(--c-ink-900)',
                }}>
                  {uploading ? 'Uploading…' : (dragOver ? 'Drop to upload' : 'Drop files here, or click to browse')}
                </div>
                <div style={{ fontSize: 12, color: 'var(--c-ink-500)', marginTop: 2 }}>
                  {ALLOWED_EXTS.map(e => e.toUpperCase()).join(' · ')} · up to 6 MB each in this preview
                </div>
              </div>
              <input
                ref={fileInputRef} type="file" multiple accept={ALLOWED_ACCEPT}
                onChange={(e) => handleFiles(e.target.files)}
                style={{ display: 'none' }}
              />
            </div>

            {/* File grid + preview pane */}
            {files.length > 0 && (
              <div style={{
                marginTop: 16, display: 'grid',
                gridTemplateColumns: 'minmax(280px, 1fr) minmax(320px, 1.4fr)',
                gap: 16, alignItems: 'stretch', minHeight: 320,
              }}>
                {/* List */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 460, overflow: 'auto', paddingRight: 4 }}>
                  {files.map(f => {
                    const meta = ALLOWED[f.ext] || { label: (f.ext || '?').toUpperCase(), color: '#666' };
                    const sel = activeFile && activeFile.id === f.id;
                    return (
                      <div key={f.id} onClick={() => setActiveFile(f)} style={{
                        display: 'flex', alignItems: 'center', gap: 12,
                        padding: '12px 12px', borderRadius: 12, cursor: 'pointer',
                        background: sel ? 'var(--c-white)' : 'var(--c-cream-50)',
                        border: sel ? '1.5px solid var(--c-petrol-800)' : '1px solid var(--border-subtle)',
                        boxShadow: sel ? 'var(--shadow-raised-sm)' : 'none',
                        transition: 'all .15s ease-out',
                      }}>
                        <FileBadge label={meta.label} color={meta.color} />
                        <div style={{ minWidth: 0, flex: 1 }}>
                          <div style={{
                            fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 500, fontSize: 13,
                            color: 'var(--c-ink-900)',
                            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                          }}>{f.name}</div>
                          <div style={{
                            fontSize: 11, color: 'var(--c-ink-500)', marginTop: 2, letterSpacing: '0.02em',
                          }}>
                            {fmtBytes(f.size)} · {fmtDate(f.uploadedAt)}
                          </div>
                        </div>
                        <button onClick={(e) => { e.stopPropagation(); removeFile(f.id); }}
                          title="Remove" style={{
                            width: 28, height: 28, borderRadius: 8, flex: 'none',
                            border: '1px solid var(--border-subtle)', background: 'var(--c-white)',
                            cursor: 'pointer',
                            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                          }}>
                          <img src="../assets/icons/cross.svg" width={10} height={10} alt="Remove" />
                        </button>
                      </div>
                    );
                  })}
                </div>

                {/* Preview pane */}
                <div style={{
                  background: 'var(--c-white)', borderRadius: 12,
                  border: '1px solid var(--border-subtle)',
                  boxShadow: 'var(--shadow-raised-sm)',
                  overflow: 'hidden', display: 'flex', flexDirection: 'column',
                }}>
                  <PreviewPane file={activeFile} preview={activePreview} />
                </div>
              </div>
            )}
          </section>

          {/* Brand kit card — logos, document templates, fonts, colors. */}
          <section style={cardStyle}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
              <h2 style={cardTitleStyle}>Brand kit</h2>
              <span style={{ fontSize: 12, color: 'var(--c-ink-500)' }}>
                {brand.length} {brand.length === 1 ? 'asset' : 'assets'} · logos, templates, fonts, palette files
              </span>
            </div>

            {/* Drop zone */}
            <div
              onDragOver={(e) => { e.preventDefault(); setBrandDragOver(true); }}
              onDragLeave={() => setBrandDragOver(false)}
              onDrop={(e) => {
                e.preventDefault();
                setBrandDragOver(false);
                handleBrandFiles(e.dataTransfer.files);
              }}
              onClick={() => brandInputRef.current?.click()}
              style={{
                border: `2px dashed ${brandDragOver ? 'var(--c-petrol-500)' : 'var(--c-cream-300)'}`,
                background: brandDragOver ? 'var(--c-petrol-050)' : 'var(--c-cream-50)',
                borderRadius: 14, padding: '22px 18px',
                display: 'flex', alignItems: 'center', gap: 14,
                cursor: 'pointer', transition: 'all .15s ease-out',
              }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12, flex: 'none',
                background: 'var(--c-olive-100, #EDEBD8)', color: 'var(--c-olive-600, #5A6A3A)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <img src="../assets/icons/library.svg" width={18} height={18} alt="" />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 500, fontSize: 14,
                  color: 'var(--c-ink-900)',
                }}>
                  {brandUploading ? 'Uploading…' : (brandDragOver ? 'Drop to add to brand kit' : 'Drop logos, templates, fonts, or any brand asset here')}
                </div>
                <div style={{ fontSize: 12, color: 'var(--c-ink-500)', marginTop: 2 }}>
                  Any file type · up to 6 MB each in this preview
                </div>
              </div>
              <input
                ref={brandInputRef} type="file" multiple
                onChange={(e) => handleBrandFiles(e.target.files)}
                style={{ display: 'none' }}
              />
            </div>

            {/* Asset grid */}
            {brand.length > 0 && (
              <div style={{
                marginTop: 16,
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(168px, 1fr))',
                gap: 12,
              }}>
                {brand.map(f => (
                  <BrandAssetCard
                    key={f.id} file={f}
                    onPreview={() => setBrandPreview(f)}
                    onRemove={() => removeBrand(f.id)}
                    onDownload={() => downloadBrand(f)}
                  />
                ))}
              </div>
            )}
          </section>
        </div>

        {/* Footer */}
        <footer style={{
          padding: '14px 24px', borderTop: '1px solid var(--border-subtle)',
          background: 'var(--c-cream-100)', display: 'flex', alignItems: 'center', gap: 10, flex: 'none',
        }}>
          <span style={{ fontSize: 12, color: 'var(--c-ink-500)' }}>
            Changes apply to <strong style={{ color: 'var(--c-ink-800)' }}>{orgName || orgId}</strong>.
          </span>
          <div style={{ flex: 1 }} />
          <button onClick={handleDone}
            disabled={savingInfo || uploading || brandUploading || loading}
            style={{
              height: 38, padding: '0 18px', borderRadius: 10, border: 'none',
              background: 'var(--c-petrol-800)', color: '#fff',
              fontFamily: "'Inter', sans-serif", fontWeight: 700, fontSize: 12,
              boxShadow: 'var(--shadow-raised-sm)',
              cursor: (savingInfo || uploading || brandUploading || loading) ? 'wait' : 'pointer',
              opacity: (savingInfo || uploading || brandUploading || loading) ? 0.7 : 1,
            }}>
            {savingInfo ? 'Saving…' : (uploading || brandUploading) ? 'Uploading…' : 'Done'}
          </button>
        </footer>
      </div>
      {brandPreview && (
        <BrandPreviewModal
          file={brandPreview}
          onClose={() => setBrandPreview(null)}
          onDownload={() => downloadBrand(brandPreview)}
          onRemove={() => { removeBrand(brandPreview.id); setBrandPreview(null); }}
        />
      )}
    </div>
  );
}

function FileBadge({ label, color }) {
  return (
    <div style={{
      width: 40, height: 48, borderRadius: 8, flex: 'none', position: 'relative',
      background: color, color: '#fff',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      padding: '0 0 6px', boxSizing: 'border-box',
      fontFamily: "'Inter', sans-serif", fontWeight: 800, fontSize: 9, letterSpacing: '0.06em',
      boxShadow: '0 1px 2px rgba(0,0,0,0.12)',
    }}>
      <span style={{
        position: 'absolute', top: 0, right: 0, width: 10, height: 10,
        background: 'rgba(255,255,255,0.35)',
        clipPath: 'polygon(0 0, 100% 100%, 100% 0)',
      }}></span>
      {label}
    </div>
  );
}

function BrandAssetCard({ file, onRemove, onDownload, onPreview }) {
  // Render a thumbnail appropriate for the asset kind. We classify on
  // upload (kind: image/font/template/doc/design/other) but also fall
  // back to the extension if `kind` is missing on older entries.
  const ext = (file.ext || extFromName(file.name)).toLowerCase();
  const kind = file.kind || (() => {
    if (['svg', 'png', 'jpg', 'jpeg', 'webp', 'gif'].includes(ext)) return 'image';
    if (['ttf', 'otf', 'woff', 'woff2'].includes(ext)) return 'font';
    if (['ai', 'eps', 'sketch', 'fig', 'xd'].includes(ext)) return 'design';
    if (ext === 'pdf') return 'doc';
    if (['doc', 'docx', 'pptx', 'ppt', 'key', 'xlsx'].includes(ext)) return 'template';
    return 'other';
  })();

  // Dynamic font face for ttf/otf/woff so the thumbnail can show "Aa"
  // rendered in the actual uploaded face.
  const fontFamily = useOM(() => {
    if (kind !== 'font' || !file.dataUrl) return null;
    const safe = (file.id || file.name).replace(/[^a-z0-9_-]/gi, '_');
    const family = `pr-brand-${safe}`;
    try {
      const fmt =
        ext === 'ttf' ? 'truetype'
        : ext === 'otf' ? 'opentype'
        : ext === 'woff' ? 'woff'
        : ext === 'woff2' ? 'woff2'
        : 'truetype';
      const css = `@font-face { font-family: '${family}'; src: url(${file.dataUrl}) format('${fmt}'); font-display: swap; }`;
      const style = document.createElement('style');
      style.setAttribute('data-pr-brand-font', family);
      style.textContent = css;
      document.head.appendChild(style);
    } catch {}
    return family;
  }, [file && file.id]);

  const tagBg = {
    image: '#E7F0EC', font: '#EAE5DA', template: '#E7EAF3',
    design: '#F1E5E0', doc: '#F4E2DC', other: '#E8E6E0',
  }[kind] || '#E8E6E0';
  const tagFg = {
    image: '#1F5C45', font: '#5A4621', template: '#28406B',
    design: '#7A3E2A', doc: '#7A2F1E', other: '#3F4A28',
  }[kind] || '#3F4A28';

  const renderThumb = () => {
    if (kind === 'image' && file.dataUrl) {
      return (
        <img src={file.dataUrl} alt={file.name}
          style={{ maxWidth: '88%', maxHeight: '88%', objectFit: 'contain' }} />
      );
    }
    if (kind === 'font' && fontFamily) {
      return (
        <div style={{
          fontFamily: `'${fontFamily}', 'Suisse Int\\'l', serif`,
          fontSize: 64, lineHeight: 1, color: 'var(--c-ink-800)', letterSpacing: '-0.02em',
        }}>Aa</div>
      );
    }
    if (kind === 'template' || kind === 'doc' || kind === 'design') {
      return (
        <div style={{
          fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 700, fontSize: 13,
          letterSpacing: '0.06em', color: tagFg,
          padding: '6px 10px', borderRadius: 8,
          background: tagBg, border: `1px solid ${tagFg}22`,
        }}>{(ext || kind).toUpperCase()}</div>
      );
    }
    return (
      <img src="../assets/icons/library.svg" width={28} height={28} alt="" style={{ opacity: 0.55 }} />
    );
  };

  return (
    <div onClick={onPreview} style={{
      position: 'relative',
      background: 'var(--c-white)',
      border: '1px solid var(--border-subtle)',
      borderRadius: 12,
      boxShadow: 'var(--shadow-raised-sm)',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      cursor: onPreview ? 'pointer' : 'default',
      transition: 'transform .12s ease-out, box-shadow .12s ease-out',
    }}>
      {/* Thumb */}
      <div style={{
        height: 120,
        background: 'var(--c-cream-50)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        borderBottom: '1px solid var(--border-subtle)',
        padding: 10,
      }}>
        {renderThumb()}
      </div>

      {/* Meta */}
      <div style={{ padding: '10px 12px 12px', display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{
          fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 500, fontSize: 13,
          color: 'var(--c-ink-900)',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }} title={file.name}>{file.name}</div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap',
          fontSize: 11, color: 'var(--c-ink-500)', letterSpacing: '0.02em',
        }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center',
            padding: '1px 6px', borderRadius: 4,
            background: tagBg, color: tagFg,
            fontWeight: 600, letterSpacing: '0.06em',
          }}>{kind}</span>
          <span>{fmtBytes(file.size)}</span>
        </div>
      </div>

      {/* Hover actions */}
      <div style={{
        position: 'absolute', top: 6, right: 6,
        display: 'flex', gap: 4,
      }}>
        {file.dataUrl && (
          <button onClick={(e) => { e.stopPropagation(); onDownload(); }} title="Download" style={brandIconBtnStyle}>
            <img src="../assets/icons/down.svg" width={11} height={11} alt="Download" />
          </button>
        )}
        <button onClick={(e) => { e.stopPropagation(); onRemove(); }} title="Remove" style={brandIconBtnStyle}>
          <img src="../assets/icons/cross.svg" width={10} height={10} alt="Remove" />
        </button>
      </div>
    </div>
  );
}

const brandIconBtnStyle = {
  width: 26, height: 26, borderRadius: 7,
  border: '1px solid var(--border-subtle)',
  background: 'rgba(255,255,255,0.92)',
  backdropFilter: 'blur(4px)',
  cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  boxShadow: 'var(--shadow-raised-sm)',
};

function DocxView({ file }) {
  // Renders a .docx (or .doc) inline via the docx-preview library, which
  // unzips the OOXML, walks the document.xml, and emits styled HTML.
  // Loaded as a global by index.html.
  const containerRef = useOR(null);
  const [busy, setBusy] = useOS(true);
  const [err, setErr] = useOS(null);

  useOE(() => {
    let cancelled = false;
    setBusy(true); setErr(null);
    (async () => {
      try {
        if (!file || !file.dataUrl) throw new Error('No content stored.');
        if (!window.docx || !window.docx.renderAsync) {
          throw new Error('Document renderer is still loading. Try again in a moment.');
        }
        // dataUrl → Blob
        const res = await fetch(file.dataUrl);
        const blob = await res.blob();
        if (cancelled || !containerRef.current) return;
        // Clear any previous render before re-rendering on file change.
        containerRef.current.innerHTML = '';
        await window.docx.renderAsync(blob, containerRef.current, null, {
          inWrapper: true,
          ignoreWidth: false,
          ignoreHeight: false,
          breakPages: true,
          experimental: true,
          className: 'pr-docx',
        });
      } catch (e) {
        if (!cancelled) setErr(String(e?.message || e));
      } finally {
        if (!cancelled) setBusy(false);
      }
    })();
    return () => { cancelled = true; };
  }, [file && file.id]);

  if (err) {
    return (
      <div style={previewEmptyStyle}>
        <img src="../assets/icons/info.svg" width={20} height={20} alt="" style={{ opacity: 0.6 }} />
        <div style={{ fontSize: 13, color: 'var(--c-ink-700)', maxWidth: 420, textAlign: 'center', textWrap: 'pretty' }}>
          {err}
        </div>
      </div>
    );
  }
  return (
    <div style={{
      flex: 1, overflow: 'auto', background: 'var(--c-cream-100)',
      padding: '20px 16px', position: 'relative',
    }}>
      {busy && (
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          alignItems: 'center', justifyContent: 'center', pointerEvents: 'none',
          color: 'var(--c-ink-500)', fontSize: 12, letterSpacing: '0.04em',
        }}>Rendering document…</div>
      )}
      <div ref={containerRef} className="pr-docx-host" style={{
        maxWidth: 820, margin: '0 auto',
      }} />
    </div>
  );
}

function PreviewPane({ file, preview }) {
  if (!file) {
    return (
      <div style={previewEmptyStyle}>
        <img src="../assets/icons/library.svg" width={28} height={28} alt="" style={{ opacity: 0.6 }} />
        <div style={{ fontSize: 13, color: 'var(--c-ink-500)' }}>Select a document to preview.</div>
      </div>
    );
  }
  const ext = (file.ext || extFromName(file.name)).toLowerCase();
  const meta = ALLOWED[ext];

  return (
    <>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '12px 14px', borderBottom: '1px solid var(--border-subtle)',
        background: 'var(--c-cream-50)', flex: 'none',
      }}>
        <FileBadge label={(meta && meta.label) || ext.toUpperCase() || '?'} color={(meta && meta.color) || '#666'} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{
            fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 500, fontSize: 13,
            color: 'var(--c-ink-900)',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{file.name}</div>
          <div style={{ fontSize: 11, color: 'var(--c-ink-500)', marginTop: 2, letterSpacing: '0.02em' }}>
            {fmtBytes(file.size)} · uploaded {fmtDate(file.uploadedAt)}{file.uploadedBy ? ` · by ${file.uploadedBy}` : ''}
          </div>
        </div>
        {file.dataUrl && (
          <a href={file.dataUrl} download={file.name} style={{
            height: 32, padding: '0 12px', borderRadius: 8,
            background: 'var(--c-petrol-800)', color: '#fff',
            fontFamily: "'Inter', sans-serif", fontWeight: 700, fontSize: 11,
            display: 'inline-flex', alignItems: 'center', gap: 6, textDecoration: 'none',
          }}>
            <img src="../assets/icons/down.svg" width={10} height={10} alt=""
              style={{ filter: 'invert(1) brightness(2)' }} />
            Download
          </a>
        )}
      </div>

      <div style={{ flex: 1, minHeight: 280, background: 'var(--c-cream-100)', overflow: 'hidden' }}>
        {preview.error && (
          <div style={previewEmptyStyle}>
            <img src="../assets/icons/info.svg" width={20} height={20} alt="" style={{ opacity: 0.6 }} />
            <div style={{ fontSize: 13, color: 'var(--c-ink-600)', maxWidth: 360, textAlign: 'center', textWrap: 'pretty' }}>
              {preview.error}
            </div>
          </div>
        )}
        {!preview.error && preview.kind === 'pdf' && preview.url && (
          <iframe src={preview.url} title={file.name}
            style={{ width: '100%', height: '100%', minHeight: 320, border: 'none', display: 'block' }} />
        )}
        {!preview.error && preview.kind === 'md' && (
          <pre style={{
            margin: 0, padding: 16,
            fontFamily: 'ui-monospace, "JetBrains Mono", Menlo, monospace',
            fontSize: 12, lineHeight: 1.55, color: 'var(--c-ink-800)',
            background: 'var(--c-white)', height: '100%', overflow: 'auto',
            whiteSpace: 'pre-wrap', wordBreak: 'break-word',
          }}>{preview.url || ''}</pre>
        )}
        {!preview.error && (preview.kind === 'doc' || preview.kind === 'docx') && (
          <DocxView file={file} />
        )}
        {!preview.error && preview.kind === 'pptx' && (
          <div style={{ ...previewEmptyStyle, gap: 10 }}>
            <FileBadge label={(meta && meta.label) || preview.kind.toUpperCase()} color={(meta && meta.color) || '#666'} />
            <div style={{ fontSize: 13, color: 'var(--c-ink-700)', textAlign: 'center', maxWidth: 360, textWrap: 'pretty' }}>
              In-browser preview isn't available for {meta?.label || preview.kind.toUpperCase()} files.
              <br />The document is stored — download it to view.
            </div>
          </div>
        )}
      </div>
    </>
  );
}

const cardStyle = {
  background: 'var(--c-white)', borderRadius: 16,
  border: '1px solid var(--border-subtle)', boxShadow: 'var(--shadow-raised-sm)',
  padding: 20,
};
const cardTitleStyle = {
  margin: 0, fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 700,
  fontSize: 18, letterSpacing: '-0.01em', color: 'var(--c-ink-900)',
};
const previewEmptyStyle = {
  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
  gap: 10, padding: 32, height: '100%', minHeight: 280, background: 'var(--c-cream-50)',
};
const primaryBtn = {
  height: 38, padding: '0 16px', borderRadius: 10, border: 'none',
  background: 'var(--c-petrol-800)', color: '#fff',
  fontFamily: "'Inter', sans-serif", fontWeight: 700, fontSize: 12,
  boxShadow: 'var(--shadow-raised-sm)', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', gap: 8,
};

function BrandPreviewModal({ file, onClose, onDownload, onRemove }) {
  // Big-format preview for a single brand-kit asset. Picks the renderer
  // based on the asset kind (image / font / pdf / md / fallback).
  const ext = (file.ext || extFromName(file.name)).toLowerCase();
  const kind = file.kind || (() => {
    if (['svg', 'png', 'jpg', 'jpeg', 'webp', 'gif'].includes(ext)) return 'image';
    if (['ttf', 'otf', 'woff', 'woff2'].includes(ext)) return 'font';
    if (ext === 'pdf') return 'doc';
    if (['doc', 'docx', 'pptx', 'ppt', 'key', 'xlsx'].includes(ext)) return 'template';
    if (['ai', 'eps', 'sketch', 'fig', 'xd'].includes(ext)) return 'design';
    return 'other';
  })();

  // Register the font face on demand so the big sample renders correctly.
  const fontFamily = useOM(() => {
    if (kind !== 'font' || !file.dataUrl) return null;
    const safe = (file.id || file.name).replace(/[^a-z0-9_-]/gi, '_');
    const family = `pr-brand-prev-${safe}`;
    try {
      const fmt =
        ext === 'ttf' ? 'truetype'
        : ext === 'otf' ? 'opentype'
        : ext === 'woff' ? 'woff'
        : ext === 'woff2' ? 'woff2' : 'truetype';
      const css = `@font-face { font-family: '${family}'; src: url(${file.dataUrl}) format('${fmt}'); font-display: swap; }`;
      const style = document.createElement('style');
      style.setAttribute('data-pr-brand-font-prev', family);
      style.textContent = css;
      document.head.appendChild(style);
    } catch {}
    return family;
  }, [file && file.id]);

  // Decode markdown content for in-browser preview (md is rare in brand kits
  // but cheap to support).
  const mdText = useOM(() => {
    if (ext !== 'md' || !file.dataUrl) return null;
    try {
      const b64 = file.dataUrl.split(',', 2)[1] || '';
      return decodeURIComponent(escape(atob(b64)));
    } catch { return null; }
  }, [file && file.id]);

  useOE(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const renderBody = () => {
    if (!file.dataUrl) {
      return (
        <div style={previewEmptyStyle}>
          <img src="../assets/icons/library.svg" width={28} height={28} alt="" style={{ opacity: 0.5 }} />
          <div style={{ fontSize: 13, color: 'var(--c-ink-500)', maxWidth: 360, textAlign: 'center' }}>
            No preview available — file content was not stored.
          </div>
        </div>
      );
    }
    if (kind === 'image') {
      const isCheckered = ['png', 'svg', 'webp', 'gif'].includes(ext);
      return (
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 24,
          backgroundImage: isCheckered
            ? 'linear-gradient(45deg, #efece4 25%, transparent 25%), linear-gradient(-45deg, #efece4 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #efece4 75%), linear-gradient(-45deg, transparent 75%, #efece4 75%)'
            : 'none',
          backgroundSize: '20px 20px',
          backgroundPosition: '0 0, 0 10px, 10px -10px, -10px 0',
          backgroundColor: 'var(--c-cream-50)',
        }}>
          <img src={file.dataUrl} alt={file.name}
            style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', boxShadow: '0 4px 24px rgba(0,0,0,0.06)' }} />
        </div>
      );
    }
    if (kind === 'font' && fontFamily) {
      const ff = `'${fontFamily}', 'Suisse Int\\'l', serif`;
      return (
        <div style={{
          flex: 1, overflow: 'auto', padding: '28px 32px',
          background: 'var(--c-cream-50)', display: 'flex', flexDirection: 'column', gap: 22,
        }}>
          <div style={{
            fontFamily: ff, fontSize: 140, lineHeight: 1, color: 'var(--c-ink-800)',
            letterSpacing: '-0.03em',
          }}>Aa Bb Cc</div>
          <div style={{ fontFamily: ff, fontSize: 56, lineHeight: 1.05, color: 'var(--c-ink-800)' }}>
            The quick brown fox jumps over the lazy dog.
          </div>
          <div style={{ fontFamily: ff, fontSize: 28, lineHeight: 1.25, color: 'var(--c-ink-700)' }}>
            ABCDEFGHIJKLMNOPQRSTUVWXYZ<br/>
            abcdefghijklmnopqrstuvwxyz<br/>
            0123456789 — &amp; @ # ! ? . ,
          </div>
          <div style={{ fontFamily: ff, fontSize: 16, lineHeight: 1.55, color: 'var(--c-ink-700)', maxWidth: 760 }}>
            Body sample. Coaching that lands depends on tone, pacing, and tiny adjustments —
            this paragraph shows how the typeface behaves at running-text size.
          </div>
        </div>
      );
    }
    if (ext === 'pdf') {
      return (
        <iframe
          title={file.name}
          src={file.dataUrl}
          style={{ flex: 1, border: 'none', background: 'var(--c-cream-50)' }}
        />
      );
    }
    if (ext === 'md' && mdText != null) {
      return (
        <pre style={{
          flex: 1, overflow: 'auto', margin: 0, padding: '20px 24px',
          fontFamily: "'JetBrains Mono', ui-monospace, monospace",
          fontSize: 13, lineHeight: 1.55, color: 'var(--c-ink-800)',
          background: 'var(--c-cream-50)', whiteSpace: 'pre-wrap', textWrap: 'pretty',
        }}>{mdText}</pre>
      );
    }
    if (ext === 'doc' || ext === 'docx') {
      return <DocxView file={file} />;
    }
    // Fallback: templates / design files / pptx have no in-browser preview
    const meta = ALLOWED[ext];
    return (
      <div style={previewEmptyStyle}>
        <FileBadge label={(meta && meta.label) || (ext || kind).toUpperCase()} color={(meta && meta.color) || '#3F4A28'} />
        <div style={{ fontSize: 13, color: 'var(--c-ink-600)', maxWidth: 420, textAlign: 'center', textWrap: 'pretty' }}>
          In-browser preview isn't available for {(meta && meta.label) || (ext || kind).toUpperCase()} files.
          The file is stored in your brand kit — download it to view.
        </div>
      </div>
    );
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(23,53,64,0.48)',
      zIndex: 240, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24, animation: 'pr-fade-in .15s ease-out',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 980, maxWidth: '100%', height: '88vh',
        background: 'var(--c-white)', border: '1px solid var(--border-subtle)',
        borderRadius: 16, boxShadow: 'var(--shadow-float-lg)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <header style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 18px', borderBottom: '1px solid var(--border-subtle)',
          background: 'var(--c-cream-100)', flex: 'none',
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: "'Suisse Int\\'l', sans-serif", fontWeight: 600, fontSize: 14,
              color: 'var(--c-ink-900)', letterSpacing: '-0.01em',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }} title={file.name}>{file.name}</div>
            <div style={{ fontSize: 11, color: 'var(--c-ink-500)', marginTop: 2, letterSpacing: '0.02em' }}>
              {kind} · {(ext || '').toUpperCase()} · {fmtBytes(file.size)} · uploaded {fmtDate(file.uploadedAt)}
            </div>
          </div>
          {file.dataUrl && (
            <button onClick={onDownload} title="Download" style={brandHeaderBtn}>
              <img src="../assets/icons/down.svg" width={12} height={12} alt="" />
              <span>Download</span>
            </button>
          )}
          <button onClick={onRemove} title="Remove" style={{ ...brandHeaderBtn, color: 'var(--c-terra-600, #C65A42)' }}>
            <img src="../assets/icons/cross.svg" width={11} height={11} alt=""
              style={{ filter: 'invert(34%) sepia(45%) saturate(1850%) hue-rotate(345deg) brightness(85%)' }} />
            <span>Remove</span>
          </button>
          <button onClick={onClose} title="Close" style={{
            width: 32, height: 32, borderRadius: 9, border: '1px solid var(--border-subtle)',
            background: 'var(--c-white)', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none',
            boxShadow: 'var(--shadow-raised-sm)',
          }}>
            <img src="../assets/icons/cross.svg" width={11} height={11} alt="Close" />
          </button>
        </header>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          {renderBody()}
        </div>
      </div>
    </div>
  );
}

const brandHeaderBtn = {
  height: 32, padding: '0 12px', borderRadius: 9,
  border: '1px solid var(--border-subtle)',
  background: 'var(--c-white)',
  fontFamily: "'Inter', sans-serif", fontWeight: 600, fontSize: 12,
  color: 'var(--c-ink-800)',
  display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
  boxShadow: 'var(--shadow-raised-sm)',
};

Object.assign(window, { OrgSettings });