// mmv-components.jsx — Shared UI components: Badge, AudioPlayer, SongDrawer, CollabDrawer, TweaksPanel

const { useState, useEffect, useRef, useMemo } = React;

// ─── Badge ────────────────────────────────────────────────────────────────────

function Badge({ children, color, bg, style: s }) {
  return (
    <span className="badge" style={{ color: color||"var(--text-3)", background: bg||"var(--bg-2)", ...(s||{}) }}>
      {children}
    </span>
  );
}

function StatusBadge({ status }) {
  const map = {
    Released:      ["#166534","#dcfce7"], Mastered:    ["#1d4ed8","#dbeafe"],
    "In Progress": ["#92400e","#fef3c7"], Mixing:      ["#92400e","#fef3c7"],
    Demo:          ["#6b7280","#f3f4f6"], Scheduled:   ["#1d4ed8","#dbeafe"],
    Submitted:     ["#1d4ed8","#dbeafe"], Shortlisted: ["#92400e","#fef3c7"],
    Cleared:       ["#166534","#dcfce7"], "In Review": ["#9d174d","#fce7f3"],
    Active:        ["#5b21b6","#ede9fe"], Pending:     ["#92400e","#fef3c7"],
    Landed:        ["#166534","#dcfce7"],
    Passed:        ["#991b1b","#fee2e2"],
    Expired:       ["#6b7280","#f3f4f6"],
  };
  const [c,b] = map[status] || ["#6b7280","#f3f4f6"];
  return <Badge color={c} bg={b}>{status}</Badge>;
}

function BriefOutcomeBadge({ status }) {
  return <StatusBadge status={status} />;
}

// ─── Embed Player ─────────────────────────────────────────────────────────────

function EmbedPlayer({ embedCode }) {
  const src    = embedCode ? (embedCode.match(/src="([^"]+)"/) || [])[1] : null;
  const height = embedCode ? ((embedCode.match(/height="(\d+)"/) || [])[1] || 235) : 235;

  if (!src) {
    return (
      <p style={{ fontSize:11, color:"var(--text-3)", textAlign:"center", margin:"12px 0" }}>
        Add an embed code in song settings to enable playback
      </p>
    );
  }

  return (
    <iframe
      src={src}
      width="100%"
      height={height}
      frameBorder="0"
      allowFullScreen
      style={{ display:"block", borderRadius:6 }}
    />
  );
}

// ─── Collab Search Dropdown ───────────────────────────────────────────────────

function SearchableSelect({
  items = [],
  filterFn,
  maxResults,
  renderItem,
  getKey,
  onSelect,
  getDisplayName,
  initialQuery,
  externalQuery,
  placeholder,
  inputStyle,
  addLabel,
  showAddWhen,
  onAddClick,
  createForm,
  showCreate,
  onCloseCreate,
  footer,
}) {
  const [query, setQuery] = useState(initialQuery || "");
  const [open,  setOpen]  = useState(false);
  const containerRef = useRef(null);

  useEffect(() => {
    if (externalQuery !== undefined && externalQuery !== query) setQuery(externalQuery);
  }, [externalQuery]);

  useEffect(() => {
    const handler = e => {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setOpen(false);
        if (onCloseCreate) onCloseCreate();
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [onCloseCreate]);

  const filtered = items.filter(item => filterFn(item, query))
    .slice(0, maxResults ?? Infinity);

  const handleSelect = (item) => {
    onSelect(item);
    setQuery(getDisplayName(item));
    setOpen(false);
  };

  const resolvedAddLabel = typeof addLabel === "function" ? addLabel(query) : addLabel;
  const showAddButton = resolvedAddLabel !== null && resolvedAddLabel !== undefined &&
    (showAddWhen === "has-query" ? !!query : true);

  return (
    <div ref={containerRef} style={{ position:"relative" }}>
      <input
        style={inputStyle || {}}
        value={query}
        placeholder={placeholder}
        onChange={e => { setQuery(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)}
      />
      {open && (
        <div style={{
          position:"absolute", top:"calc(100% + 4px)", left:0, right:0, zIndex:300,
          background:"var(--card)", border:"1px solid var(--border)", borderRadius:8,
          boxShadow:"0 8px 24px rgba(0,0,0,0.15)", overflow:"hidden",
        }}>
          {filtered.map(item => (
            <div key={getKey(item)} onMouseDown={() => handleSelect(item)}
              style={{ padding:"9px 12px", cursor:"pointer" }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            >
              {renderItem(item)}
            </div>
          ))}
          {filtered.length === 0 && !showCreate && (
            <div style={{ padding:"9px 12px", fontSize:12, color:"var(--text-3)" }}>No match found</div>
          )}
          {showAddButton && !showCreate && (
            <div
              onMouseDown={() => onAddClick(query)}
              style={{ padding:"9px 12px", cursor:"pointer", borderTop:"1px solid var(--border)", fontSize:12, color:"var(--accent)" }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            >
              {resolvedAddLabel}
            </div>
          )}
          {showCreate && createForm && (
            <div style={{ borderTop:"1px solid var(--border)" }}>
              {createForm}
            </div>
          )}
          {footer}
        </div>
      )}
    </div>
  );
}

function CollabSearchDropdown({ split, collabs, onUpdateSplit, onNewCollab, inputStyle }) {
  const [showNewForm, setShowNewForm] = useState(false);
  const [newForm,     setNewForm]     = useState({ name:"", role:"Co-Writer", email:"" });

  const handleSelect = (collab) => {
    onUpdateSplit({
      ...split,
      collabId:  collab.id,
      writer:    (split.writer != null && split.writer !== 0) ? split.writer : (collab.defaultWriter || 0),
      publisher: (split.publisher != null && split.publisher !== 0) ? split.publisher : (collab.defaultPublisher || 0),
    });
  };

  const handleCreate = () => {
    if (!newForm.name.trim()) return;
    const created = {
      id: Date.now(), name: newForm.name.trim(), role: newForm.role.trim() || "Co-Writer",
      email: newForm.email.trim(), incomplete: true, selfPublished: false,
      pro: "", ipi: "", publishingEntity: "", company: "Independent",
      phone: "", website: "", instagram: "", spotify: "", location: "", country: "",
      status: "Active", splits: 0, defaultWriter: 50, defaultPublisher: 50,
      tags: [], manager: "", publisherId: null, relationshipStatus: "New Collaborator",
      notes: "", createdAt: Date.now(),
    };
    if (onNewCollab) onNewCollab(created);
    handleSelect(created);
    setNewForm({ name:"", role:"Co-Writer", email:"" });
    setShowNewForm(false);
  };

  const baseInput = inputStyle || {};

  return (
    <SearchableSelect
      items={collabs || []}
      filterFn={(c, q) => c.name.toLowerCase().includes(q.toLowerCase())}
      maxResults={8}
      getKey={c => c.id}
      renderItem={c => (
        <>
          <div style={{ fontSize:12, fontWeight:500 }}>
            {c.name}
            {c.incomplete && <span style={{ marginLeft:6, fontSize:9.5, color:"#d97706", background:"#fef3c7", padding:"1px 5px", borderRadius:3 }}>Incomplete</span>}
          </div>
          <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{c.role}{c.pro ? " · " + c.pro : ""}</div>
        </>
      )}
      onSelect={handleSelect}
      getDisplayName={c => c.name}
      initialQuery={getSplitName(split, collabs)}
      placeholder="Search collaborators…"
      inputStyle={baseInput}
      addLabel={q => `+ Add "${q || "new collaborator"}"`}
      showAddWhen="always"
      onAddClick={q => { setShowNewForm(true); setNewForm(f => ({ ...f, name: q })); }}
      showCreate={showNewForm}
      onCloseCreate={() => setShowNewForm(false)}
      createForm={
        <div style={{ padding:"10px 12px", display:"flex", flexDirection:"column", gap:6 }}>
          <div style={{ fontSize:10.5, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.06em", marginBottom:2 }}>Quick-add collaborator</div>
          {[["Name *","name","Full name"],["Role","role","Co-Writer, Producer…"],["Email","email","email@example.com"]].map(([lbl,key,ph]) => (
            <input key={key}
              style={{ ...baseInput, padding:"5px 8px", fontSize:11 }}
              placeholder={ph}
              value={newForm[key]}
              onChange={e => setNewForm(f => ({ ...f, [key]: e.target.value }))}
            />
          ))}
          <div style={{ display:"flex", gap:6 }}>
            <button onMouseDown={handleCreate}
              style={{ flex:1, padding:"5px", borderRadius:5, border:"none", background:"var(--accent)", color:"#fff", fontSize:11, cursor:"pointer" }}>
              Add &amp; Select
            </button>
            <button onMouseDown={() => setShowNewForm(false)}
              style={{ padding:"5px 10px", borderRadius:5, border:"1px solid var(--border)", background:"none", color:"var(--text-3)", fontSize:11, cursor:"pointer" }}>
              Cancel
            </button>
          </div>
        </div>
      }
    />
  );
}

// ─── Artist Search Dropdown ───────────────────────────────────────────────────

function ArtistSearchDropdown({ artistId, artistName, artists, onUpdate, onNewArtist, inputStyle }) {
  const [showNew, setShowNew] = useState(false);
  const [newName, setNewName] = useState("");

  const handleSelect = (artist) => {
    onUpdate({ artistId: artist.id, artist: artist.name });
  };

  const handleCreate = () => {
    if (!newName.trim()) return;
    const created = {
      id: Date.now(), name: newName.trim(),
      genre: "", description: "", active: true,
      artworkHue: Math.floor(Math.random() * 360), createdAt: Date.now(),
    };
    if (onNewArtist) onNewArtist(created);
    handleSelect(created);
    setNewName("");
    setShowNew(false);
  };

  const baseInput = inputStyle || {};

  return (
    <SearchableSelect
      items={artists || []}
      filterFn={(a, q) => a.name.toLowerCase().includes(q.toLowerCase())}
      getKey={a => a.id}
      renderItem={a => (
        <>
          <div style={{ fontSize:12, fontWeight:500 }}>{a.name}</div>
          {a.genre && <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{a.genre}</div>}
        </>
      )}
      onSelect={handleSelect}
      getDisplayName={a => a.name}
      initialQuery={artistName || ""}
      externalQuery={artistName || ""}
      placeholder="Search artists…"
      inputStyle={baseInput}
      addLabel={q => q ? `+ Add "${q}" as new artist` : null}
      showAddWhen="has-query"
      onAddClick={q => { setShowNew(true); setNewName(q); }}
      showCreate={showNew}
      onCloseCreate={() => setShowNew(false)}
      createForm={
        <div style={{ padding:"10px 12px", display:"flex", gap:6 }}>
          <input
            style={{ ...baseInput, flex:1, padding:"5px 8px", fontSize:11 }}
            placeholder="Artist name"
            value={newName}
            onChange={e => setNewName(e.target.value)}
          />
          <button onMouseDown={handleCreate}
            style={{ padding:"5px 10px", borderRadius:5, border:"none", background:"var(--accent)", color:"#fff", fontSize:11, cursor:"pointer" }}>
            Add
          </button>
        </div>
      }
      footer={artistId ? (
        <div
          onMouseDown={() => { onUpdate({ artistId: null, artist: "" }); }}
          style={{ padding:"8px 12px", borderTop:"1px solid var(--border)", fontSize:11, color:"var(--text-3)", cursor:"pointer" }}
          onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
          onMouseLeave={e => e.currentTarget.style.background = "transparent"}
        >
          ✕ Clear artist
        </div>
      ) : null}
    />
  );
}

// ─── Song Drawer ──────────────────────────────────────────────────────────────

function RegItem({ label, checked, auto, onToggle, link }) {
  return (
    <div
      onClick={!auto ? onToggle : undefined}
      style={{
        display:"flex", alignItems:"center", justifyContent:"space-between",
        padding:"9px 13px", borderBottom:"1px solid var(--border-sub)",
        cursor: auto ? "default" : "pointer", background:"var(--card)", transition:"background 0.08s",
      }}
      onMouseEnter={e => { if (!auto) e.currentTarget.style.background = "var(--bg-2)"; }}
      onMouseLeave={e => { e.currentTarget.style.background = "var(--card)"; }}
    >
      <div style={{ display:"flex", alignItems:"center", gap:9 }}>
        <div style={{
          width:16, height:16, borderRadius:4, flexShrink:0,
          background: checked ? (auto ? "var(--text-3)" : "var(--accent)") : "transparent",
          border: checked ? "none" : "1.5px solid var(--border)",
          display:"flex", alignItems:"center", justifyContent:"center", transition:"all 0.12s",
        }}>
          {checked && <span style={{ color:"#fff", fontSize:9, fontWeight:800, lineHeight:1 }}>✓</span>}
        </div>
        <span style={{ fontSize:13, fontWeight:450, color: checked ? "var(--text)" : "var(--text-3)" }}>{label}</span>
      </div>
      <div style={{ display:"flex", alignItems:"center", gap:6 }}>
        {link && <a href={link} target="_blank" rel="noopener noreferrer" onClick={e=>e.stopPropagation()} style={{ fontSize:11, color:"var(--accent)", textDecoration:"none", background:"var(--accent-dim)", border:"1px solid var(--accent)", borderRadius:4, padding:"1px 6px" }}>↗ View</a>}
        {auto && <span style={{ fontSize:9.5, color:"var(--text-3)", background:"var(--bg-2)", border:"1px solid var(--border)", borderRadius:4, padding:"1px 6px", letterSpacing:"0.04em", fontWeight:500 }}>auto</span>}
      </div>
    </div>
  );
}

function SongDrawer({ song, briefs, collabs: collabsProp, artists: artistsProp, onNewCollab, onNewArtist, onClose, onDelete, onUpdate, isCentered, onToggleCenter }) {
  const collabs = collabsProp || COLLABS;
  const artists = artistsProp || ARTISTS;
  if (!song) return null;
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [draft, setDraft] = useState(null);

  useEffect(() => {
    setEditMode(false);
    setConfirmDelete(false);
    setDraft(null);
  }, [song.id]);

  const set = (key, val) => setDraft(d => ({...d, [key]: val}));

  const viewTotal = song.splits.reduce((a,s) => a + s.writer, 0);
  const editTotal = draft ? draft.splits.reduce((a,s) => a + (parseFloat(s.writer)||0), 0) : 0;
  const total = editMode ? editTotal : viewTotal;
  const valid = Math.abs(total - 100) < 0.01;

  const openEdit = () => {
    setDraft({ ...song, splits: song.splits.map(s=>({...s})), moods: song.moods.join(", ") });
    setEditMode(true);
    setConfirmDelete(false);
  };

  const handleSave = () => {
    if (!draft || !onUpdate) return;
    onUpdate(song.id, {
      ...draft,
      bpm: parseInt(draft.bpm) || 0,
      ownershipPct: parseFloat(draft.ownershipPct) || 0,
      moods: typeof draft.moods === "string"
        ? draft.moods.split(",").map(m => m.trim()).filter(Boolean)
        : draft.moods,
      splits: draft.splits.map(s => ({...s, writer: parseFloat(s.writer)||0, publisher: parseFloat(s.publisher)||0})),
    });
    setEditMode(false);
  };

  const STATUS_OPTIONS = ["Demo","In Progress","Mixing","Mastered","Released"];
  const inp = { width:"100%", padding:"6px 9px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg)", color:"var(--text)", fontSize:13, fontFamily:"var(--font)", outline:"none" };
  const monoInp = { ...inp, fontFamily:"var(--mono)", fontSize:12 };
  const lbl = { fontSize:9.5, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.07em", fontWeight:500, marginBottom:4, display:"block" };
  const setSplit = (i, key, val) => setDraft(d => { const sp=[...d.splits]; sp[i]={...sp[i],[key]:val}; return {...d,splits:sp}; });
  const replaceSplit = (i, updated) => setDraft(d => { const sp=[...d.splits]; sp[i]=updated; return {...d,splits:sp}; });

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>
        <div className="drawer-header">
          <div>
            <div className="drawer-title">{editMode && draft ? draft.title : song.title}</div>
            <div style={{ fontSize:12, color:"var(--text-3)", marginTop:2 }}>
              {song.version} · {song.genre}{song.artist ? <span> · <span style={{ color:"var(--accent)" }}>{song.artist}</span></span> : ""}
            </div>
          </div>
          <div style={{ display:"flex", alignItems:"center", gap:6 }}>
            {!editMode ? (
              <>
                <button className="btn-ghost" style={{ fontSize:11 }} onClick={() => exportSongPDF(song)}>↓ PDF</button>
                {confirmDelete
                  ? <>
                      <button className="btn-ghost" style={{ fontSize:11, color:"var(--text-3)" }} onClick={() => setConfirmDelete(false)}>Cancel</button>
                      <button className="btn-ghost" style={{ fontSize:11, color:"#e05c5c", borderColor:"#e05c5c" }} onClick={() => { onDelete(song.id); onClose(); }}>Confirm delete</button>
                    </>
                  : <button className="btn-ghost" style={{ fontSize:11, color:"#e05c5c" }} onClick={() => setConfirmDelete(true)}>Delete</button>
                }
                <button className="btn-ghost" style={{ fontSize:11 }} onClick={openEdit}>Edit</button>
              </>
            ) : (
              <>
                <button className="btn-ghost" style={{ fontSize:11, color:"var(--text-3)" }} onClick={() => setEditMode(false)}>Cancel</button>
                <button className="btn-ghost" style={{ fontSize:11, color:"var(--accent)", borderColor:"var(--accent)" }} onClick={handleSave}>Save</button>
              </>
            )}
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        <div style={{ padding:"16px 20px", borderBottom:"1px solid var(--border)" }}>
          <EmbedPlayer embedCode={editMode && draft ? (draft.embedCode||"") : (song.embedCode||"")} />
        </div>

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1 }}>

          {/* ── VIEW MODE ── */}
          {!editMode && (
            <>
              <div className="meta-grid">
                {[
                  ["ISRC",     song.isrc||"—",          true],
                  ["ISWC",     song.iswc||"—",          true],
                  ["BPM",      song.bpm,                true],
                  ["Key",      song.key,                false],
                  ["PRO",      song.pro,                false],
                  ["Duration", song.duration,           true],
                  ["Master %",  +parseFloat(song.ownershipPct).toFixed(2) + "%",                                                                                              true],
                  ["Pub %",    +parseFloat(song.splits.find(s => getSplitName(s, collabs) === song.masterOwner)?.publisher ?? song.ownershipPct).toFixed(2) + "%", true],
                ].map(([label, val, mono]) => (
                  <div key={label} className="meta-cell">
                    <div className="meta-label">{label}</div>
                    <div className={"meta-value" + (mono?" mono":"")}>{val}</div>
                  </div>
                ))}
              </div>

              <div style={{ display:"flex", gap:5, flexWrap:"wrap", margin:"12px 0" }}>
                <StatusBadge status={song.status} />
                {song.syncReady      && <Badge color="#166534" bg="#dcfce7">Sync Ready</Badge>}
                {song.stemsAvailable && <Badge color={SPLIT_COLORS[0]} bg="#ede9fe">Stems</Badge>}
                {song.instrumental   && <Badge>Instrumental</Badge>}
                {song.moods.map(m => <Badge key={m}>{m}</Badge>)}
              </div>

              <div className="section-label">Writer & Publisher Splits</div>
              {viewTotal !== 100 && <div className="alert-warn">⚠ Total is {viewTotal}% — must equal 100%</div>}
              <div className="split-bar">
                {song.splits.map((s,i) => <div key={i} style={{ width:`${s.writer}%`, height:"100%", background:SPLIT_COLORS[i], borderRadius:2 }}></div>)}
                {viewTotal < 100 && <div style={{ flex:1, background:"var(--border)" }}></div>}
              </div>
              {song.splits.map((s,i) => {
                const linkedCollab = s.collabId ? collabs.find(x => x.id === s.collabId) : null;
                const linkedPub = linkedCollab && linkedCollab.publisherId ? PUBLISHERS.find(p => p.id === linkedCollab.publisherId) : null;
                return (
                  <div key={i} className="split-row">
                    <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                      <div style={{ width:8, height:8, borderRadius:"50%", background:SPLIT_COLORS[i], flexShrink:0 }}></div>
                      <div>
                        <div style={{ fontWeight:500, fontSize:13 }}>{getSplitName(s, collabs)}</div>
                        <div style={{ fontSize:11, color:"var(--text-3)" }}>{linkedCollab?.role ?? s.role}</div>
                        {linkedCollab && (
                          <div style={{ fontSize:10, color:"var(--text-3)", marginTop:2 }}>
                            {[linkedCollab.pro, linkedCollab.ipi ? `IPI: ${linkedCollab.ipi}` : null, linkedPub ? linkedPub.name : null].filter(Boolean).join(" · ")}
                            {linkedCollab.incomplete && <span style={{ marginLeft:5, color:"#d97706" }}>⚠ Info missing</span>}
                          </div>
                        )}
                      </div>
                    </div>
                    <div style={{ textAlign:"right" }}>
                      <div className="mono" style={{ fontWeight:700, fontSize:13, color:SPLIT_COLORS[i] }}>{+parseFloat(s.writer).toFixed(2)}%</div>
                      <div style={{ fontSize:10, color:"var(--text-3)" }}>Pub {+parseFloat(s.publisher).toFixed(2)}%</div>
                    </div>
                  </div>
                );
              })}

              <div className="section-label" style={{ marginTop:16 }}>Rights</div>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8 }}>
                {[["Master Owner", song.masterOwner], ["Publishing", song.publishingOwner]].map(([l,v]) => (
                  <div key={l} className="info-box">
                    <div className="meta-label">{l}</div>
                    <div style={{ fontSize:13, fontWeight:500 }}>{v}</div>
                  </div>
                ))}
              </div>

              {song.notes && (
                <>
                  <div className="section-label" style={{ marginTop:16 }}>Notes</div>
                  <div className="info-box" style={{ fontSize:13, lineHeight:1.65, color:"var(--text-2)" }}>{song.notes}</div>
                </>
              )}

              {song.lyrics && (
                <>
                  <div className="section-label" style={{ marginTop:16 }}>Lyrics</div>
                  <div className="info-box" style={{ fontSize:13, lineHeight:1.8, color:"var(--text-2)", whiteSpace:"pre-wrap" }}>{song.lyrics}</div>
                </>
              )}

              {/* Sync History */}
              {(() => {
                const songBriefs = (briefs||[]).filter(b =>
                  (b.submittedSongs||[]).some(ss => String(ss.songId) === String(song.id))
                );
                if (songBriefs.length === 0) return null;
                return (
                  <>
                    <div className="section-label" style={{ marginTop:16 }}>Sync History ({songBriefs.length})</div>
                    <div style={{ display:"flex", flexDirection:"column", gap:5 }}>
                      {songBriefs.map(b => {
                        const ss = b.submittedSongs.find(s => String(s.songId) === String(song.id));
                        return (
                          <div key={b.id} className="info-box" style={{ padding:"9px 12px", display:"flex", justifyContent:"space-between", alignItems:"center", gap:8 }}>
                            <div style={{ flex:1, minWidth:0 }}>
                              <div style={{ fontSize:13, fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{b.title}</div>
                              <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{b.client||"—"} · {ss?.submittedAt||"—"}</div>
                            </div>
                            <StatusBadge status={b.status} />
                          </div>
                        );
                      })}
                    </div>
                  </>
                );
              })()}

              <div className="section-label" style={{ marginTop:16 }}>Registration</div>
              <div style={{ border:"1px solid var(--border)", borderRadius:8, overflow:"hidden" }}>
                <RegItem label="ISRC assigned"        checked={!!song.isrc}                                  auto={true} />
                <RegItem label="ISWC lodged"          checked={!!song.iswc}                                  auto={true} />
                <RegItem label="PRO registered"       checked={!!song.proRegistered}                         auto={false} onToggle={() => onUpdate && onUpdate(song.id, { proRegistered: !song.proRegistered })} />
                <RegItem label="Publisher registered" checked={!!song.pubRegistered}                         auto={false} onToggle={() => onUpdate && onUpdate(song.id, { pubRegistered: !song.pubRegistered })} />
                <RegItem label="Split sheet signed"   checked={!!(song.splitSheetUrl||song.splitSheetSigned)} auto={false} link={song.splitSheetUrl||""} onToggle={() => onUpdate && onUpdate(song.id, { splitSheetSigned: !(song.splitSheetUrl||song.splitSheetSigned), splitConflict: !!(song.splitSheetUrl||song.splitSheetSigned) })} />
                <RegItem label="Stems exported"       checked={!!song.stemsAvailable}                        auto={true} />
              </div>

              {/* ── CWR Registration [PUBLISHER] ── */}
              <div style={{ display:"flex", alignItems:"center", gap:6, marginTop:16, marginBottom:6 }}>
                <span className="section-label" style={{ margin:0 }}>CWR Registration</span>
                <span style={{ fontSize:9.5, fontWeight:700, background:"#7c3aed", color:"#fff", padding:"1px 6px", borderRadius:4, letterSpacing:"0.04em" }}>PUBLISHER</span>
              </div>
              <div style={{ border:"1px solid var(--border)", borderRadius:8, overflow:"hidden" }}>
                {[
                  ["Version Type", song.versionType === "MOD" ? "Modified (MOD)" : "Original (ORI)"],
                  ["Territories",  (song.cwrTerritories||[]).length === 0
                    ? "World — all territories (default)"
                    : (song.cwrTerritories||[]).map(t => {
                        const terr = CWR_TERRITORIES.find(x => x.code === t.code);
                        return (terr ? terr.name : t.code) + " (" + (t.mode||"include") + ")";
                      }).join(", ")
                  ],
                  ["Last exported", song.cwrExportedAt
                    ? new Date(song.cwrExportedAt).toLocaleDateString("en-AU", { day:"numeric", month:"short", year:"numeric" })
                    : "Never exported"
                  ],
                  ["File ref", song.cwrFileRef || "—"],
                ].map(([l, v]) => (
                  <div key={l} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"9px 13px", borderBottom:"1px solid var(--border-sub)", fontSize:12.5 }}>
                    <span style={{ color:"var(--text-3)" }}>{l}</span>
                    <span style={{ color:"var(--text-2)", fontWeight:500, textAlign:"right", maxWidth:"60%" }}>{v}</span>
                  </div>
                ))}
                <div style={{ padding:"9px 13px", fontSize:12.5 }}>
                  <div style={{ color:"var(--text-3)", marginBottom:4 }}>Writer CWR fields</div>
                  <div style={{ display:"flex", flexDirection:"column", gap:4 }}>
                    {song.splits.map((s, i) => {
                      const name = getSplitName(s, collabs);
                      const code = s.cwrDesignationCode || "CA";
                      const ctrl = s.cwrControlled !== false;
                      return (
                        <div key={i} style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
                          <span style={{ color:"var(--text-2)", fontSize:12 }}>{name}</span>
                          <span style={{ display:"flex", gap:5 }}>
                            <span className="mono" style={{ fontSize:10.5, background:"var(--bg-2)", border:"1px solid var(--border)", borderRadius:4, padding:"1px 5px" }}>{code}</span>
                            <span style={{ fontSize:10.5, color: ctrl ? "#059669" : "#6b7280" }}>{ctrl ? "SWR" : "OWR"}</span>
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </>
          )}

          {/* ── EDIT MODE ── */}
          {editMode && draft && (
            <>
              <div className="section-label">Basic Info</div>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8, marginBottom:10 }}>
                <div style={{ gridColumn:"1/-1" }}>
                  <label style={lbl}>Title</label>
                  <input style={inp} value={draft.title} onChange={e => set("title", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Version</label>
                  <input style={inp} value={draft.version} onChange={e => set("version", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Artist</label>
                  <ArtistSearchDropdown
                    artistId={draft.artistId}
                    artistName={draft.artist||""}
                    artists={artists}
                    onUpdate={({ artistId, artist }) => { set("artistId", artistId); set("artist", artist); }}
                    onNewArtist={onNewArtist}
                    inputStyle={inp}
                  />
                </div>
                <div>
                  <label style={lbl}>Genre</label>
                  <input style={inp} value={draft.genre} onChange={e => set("genre", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Release Date</label>
                  <input style={inp} type="date" value={draft.releaseDate||""} onChange={e => set("releaseDate", e.target.value||null)} />
                </div>
                <div>
                  <label style={lbl}>Album</label>
                  <input style={inp} value={draft.album||""} onChange={e => set("album", e.target.value)} />
                </div>
                <div style={{ gridColumn:"1/-1" }}>
                  <label style={lbl}>International Title</label>
                  <input style={inp} value={draft.internationalTitle||""} onChange={e => set("internationalTitle", e.target.value)} />
                </div>
              </div>

              <div className="section-label">Technical</div>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8, marginBottom:10 }}>
                <div>
                  <label style={lbl}>ISRC</label>
                  <input style={monoInp} value={draft.isrc||""} onChange={e => set("isrc", e.target.value)} placeholder="XX-XXX-XX-XXXXX" />
                </div>
                <div>
                  <label style={lbl}>ISWC</label>
                  <input style={monoInp} value={draft.iswc||""} onChange={e => set("iswc", e.target.value)} placeholder="T-XXX.XXX.XXX-X" />
                </div>
                <div>
                  <label style={lbl}>BPM</label>
                  <input style={inp} type="number" min="40" max="300" value={draft.bpm} onChange={e => set("bpm", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Key</label>
                  <input style={inp} value={draft.key} onChange={e => set("key", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Duration</label>
                  <input style={monoInp} value={draft.duration} onChange={e => set("duration", e.target.value)} placeholder="0:00" />
                </div>
                <div>
                  <label style={lbl}>PRO</label>
                  <input style={inp} value={draft.pro||""} onChange={e => set("pro", e.target.value)} />
                </div>
                <div style={{ gridColumn:"1/-1" }}>
                  <label style={lbl}>Embed Code (Disco, Spotify, SoundCloud, etc.)</label>
                  <textarea style={{...monoInp, resize:"vertical", minHeight:72}} value={draft.embedCode||""} onChange={e => set("embedCode", e.target.value)} placeholder="Paste full <iframe> embed code here…" />
                  <div style={{ fontSize:10, color:"var(--text-3)", marginTop:3 }}>Player above updates as you type</div>
                </div>
              </div>

              <div className="section-label">Status & Rights</div>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8, marginBottom:6 }}>
                <div>
                  <label style={lbl}>Status</label>
                  <select style={inp} value={draft.status} onChange={e => set("status", e.target.value)}>
                    {STATUS_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)}
                  </select>
                </div>
                <div>
                  <label style={lbl}>Ownership %</label>
                  <input style={inp} type="number" min="0" max="100" step="0.01" value={draft.ownershipPct} onChange={e => set("ownershipPct", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Master Owner</label>
                  <input style={inp} value={draft.masterOwner||""} onChange={e => set("masterOwner", e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Publishing Owner</label>
                  <input style={inp} value={draft.publishingOwner||""} onChange={e => set("publishingOwner", e.target.value)} />
                </div>
                <div style={{ gridColumn:"1/-1" }}>
                  <label style={lbl}>Signed Splitsheet URL</label>
                  <input style={monoInp} value={draft.splitSheetUrl||""} onChange={e => set("splitSheetUrl", e.target.value)} placeholder="https://drive.google.com/…" />
                </div>
              </div>
              <div style={{ display:"flex", gap:18, margin:"8px 0 12px" }}>
                {[["syncReady","Sync Ready"],["stemsAvailable","Stems Available"],["instrumental","Instrumental"]].map(([k,l]) => (
                  <label key={k} style={{ display:"flex", alignItems:"center", gap:6, fontSize:13, cursor:"pointer", color:"var(--text-2)" }}>
                    <input type="checkbox" checked={!!draft[k]} onChange={e => set(k, e.target.checked)} style={{ accentColor:"var(--accent)", width:14, height:14, cursor:"pointer" }} />
                    {l}
                  </label>
                ))}
              </div>

              <div className="section-label">Moods</div>
              <div style={{ marginBottom:10 }}>
                <input style={inp} value={typeof draft.moods === "string" ? draft.moods : draft.moods.join(", ")} onChange={e => set("moods", e.target.value)} placeholder="Dark, Cinematic, Uplifting…" />
                <div style={{ fontSize:11, color:"var(--text-3)", marginTop:3 }}>Comma-separated</div>
              </div>

              <div className="section-label">Notes</div>
              <textarea style={{ ...inp, minHeight:72, resize:"vertical", lineHeight:1.6, marginBottom:10 }} value={draft.notes||""} onChange={e => set("notes", e.target.value)} placeholder="Any notes about this song…" />

              <div className="section-label">Lyrics</div>
              <textarea style={{ ...inp, minHeight:120, resize:"vertical", lineHeight:1.8, marginBottom:10, fontFamily:"var(--font)" }} value={draft.lyrics||""} onChange={e => set("lyrics", e.target.value)} placeholder="Paste or type lyrics here…" />

              {/* ── CWR section [PUBLISHER] ── */}
              <div style={{ display:"flex", alignItems:"center", gap:6, marginBottom:6 }}>
                <span className="section-label" style={{ margin:0 }}>CWR Registration</span>
                <span style={{ fontSize:9.5, fontWeight:700, background:"#7c3aed", color:"#fff", padding:"1px 6px", borderRadius:4, letterSpacing:"0.04em" }}>PUBLISHER</span>
              </div>
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:8, marginBottom:10 }}>
                <div>
                  <label style={lbl}>Version Type</label>
                  <select style={inp} value={draft.versionType||"ORI"} onChange={e => set("versionType", e.target.value)}>
                    <option value="ORI">ORI — Original</option>
                    <option value="MOD">MOD — Modified</option>
                  </select>
                </div>
                <div>
                  <label style={lbl}>CWR File Ref</label>
                  <input style={{ ...inp, fontFamily:"monospace" }} value={draft.cwrFileRef||""} onChange={e => set("cwrFileRef", e.target.value)} placeholder="e.g. CWR_20260101" />
                </div>
              </div>
              <div style={{ marginBottom:10 }}>
                <label style={lbl}>Territories (empty = World default)</label>
                <div style={{ display:"flex", flexDirection:"column", gap:4, marginBottom:4 }}>
                  {(draft.cwrTerritories||[]).map((t, ti) => {
                    const terr = CWR_TERRITORIES.find(x => x.code === t.code);
                    return (
                      <div key={ti} style={{ display:"flex", gap:6, alignItems:"center" }}>
                        <span style={{ flex:1, fontSize:12.5, color:"var(--text-2)" }}>{terr ? terr.name : t.code} <span className="mono" style={{ fontSize:10.5, color:"var(--text-3)" }}>({t.code})</span></span>
                        <select
                          value={t.mode||"include"}
                          onChange={e => { const ts=[...(draft.cwrTerritories||[])]; ts[ti]={...ts[ti],mode:e.target.value}; set("cwrTerritories", ts); }}
                          style={{ padding:"2px 5px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:11.5, fontFamily:"var(--font)" }}
                        >
                          <option value="include">Include</option>
                          <option value="exclude">Exclude</option>
                        </select>
                        <button onClick={() => { const ts=(draft.cwrTerritories||[]).filter((_,j)=>j!==ti); set("cwrTerritories", ts); }} style={{ background:"none", border:"none", cursor:"pointer", color:"var(--text-3)", fontSize:14, lineHeight:1, padding:"0 2px" }} title="Remove">×</button>
                      </div>
                    );
                  })}
                </div>
                <select
                  value=""
                  onChange={e => {
                    if (!e.target.value) return;
                    const exists = (draft.cwrTerritories||[]).some(t => t.code === e.target.value);
                    if (!exists) set("cwrTerritories", [...(draft.cwrTerritories||[]), { code: e.target.value, mode: "include" }]);
                  }}
                  style={{ ...inp, fontSize:12, color:"var(--text-3)" }}
                >
                  <option value="">+ Add territory…</option>
                  {CWR_TERRITORIES.filter(t => !(draft.cwrTerritories||[]).some(x => x.code === t.code)).map(t => (
                    <option key={t.code} value={t.code}>{t.name} ({t.code})</option>
                  ))}
                </select>
                {(draft.cwrTerritories||[]).length === 0 && (
                  <div style={{ fontSize:11, color:"var(--text-3)", marginTop:4 }}>No territories selected — defaults to World (2136) on export</div>
                )}
              </div>

              <div className="section-label">Writer & Publisher Splits</div>
              {!valid && <div className="alert-warn" style={{ marginBottom:8 }}>⚠ Total is {+parseFloat(editTotal).toFixed(2)}% — must equal 100%</div>}
              <div style={{ display:"flex", flexDirection:"column", gap:6, marginBottom:8 }}>
                {draft.splits.map((s, i) => (
                  <div key={i} style={{ background:"var(--bg-2)", border:"1px solid var(--border)", borderRadius:7, padding:"9px 10px" }}>
                    <div style={{ display:"grid", gridTemplateColumns:"1fr auto", gap:6, marginBottom:5, alignItems:"center" }}>
                      <CollabSearchDropdown
                        split={s}
                        collabs={collabs}
                        onUpdateSplit={updated => replaceSplit(i, updated)}
                        onNewCollab={onNewCollab}
                        inputStyle={{ ...inp, padding:"4px 7px", fontSize:12 }}
                      />
                      <button onClick={() => setDraft(d => ({...d, splits:d.splits.filter((_,j)=>j!==i)}))} style={{ background:"none", border:"none", cursor:"pointer", color:"var(--text-3)", fontSize:16, padding:"0 2px", lineHeight:1 }} title="Remove writer">×</button>
                    </div>
                    <input style={{ ...inp, padding:"3px 7px", fontSize:11, color:"var(--text-2)", marginBottom:7 }} value={s.role} placeholder="Role" onChange={e => setSplit(i,"role",e.target.value)} />
                    <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:6, marginBottom:6 }}>
                      <div>
                        <label style={{ ...lbl, marginBottom:2 }}>Writer %</label>
                        <input style={{ ...monoInp, padding:"4px 7px" }} type="number" min="0" max="100" step="0.01" value={s.writer} onChange={e => setSplit(i,"writer",e.target.value)} />
                      </div>
                      <div>
                        <label style={{ ...lbl, marginBottom:2 }}>Publisher %</label>
                        <input style={{ ...monoInp, padding:"4px 7px" }} type="number" min="0" max="100" step="0.01" value={s.publisher} onChange={e => setSplit(i,"publisher",e.target.value)} />
                      </div>
                    </div>
                    <div style={{ borderTop:"1px solid var(--border)", paddingTop:6, display:"flex", gap:8, alignItems:"center", flexWrap:"wrap" }}>
                      <span style={{ fontSize:9.5, fontWeight:700, background:"#7c3aed", color:"#fff", padding:"1px 5px", borderRadius:3, letterSpacing:"0.04em", flexShrink:0 }}>PUBLISHER</span>
                      <div style={{ display:"flex", gap:6, alignItems:"center", flex:1, flexWrap:"wrap" }}>
                        <div>
                          <label style={{ ...lbl, marginBottom:1, display:"block" }}>Designation</label>
                          <select
                            value={s.cwrDesignationCode||"CA"}
                            onChange={e => setSplit(i,"cwrDesignationCode",e.target.value)}
                            style={{ padding:"3px 6px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg)", color:"var(--text)", fontSize:11.5, fontFamily:"var(--font)" }}
                          >
                            {CWR_DESIGNATION_CODES.map(d => <option key={d.code} value={d.code}>{d.code} — {d.label}</option>)}
                          </select>
                        </div>
                        <label style={{ display:"flex", alignItems:"center", gap:5, fontSize:11.5, cursor:"pointer", color:"var(--text-2)", marginTop:12 }}>
                          <input
                            type="checkbox"
                            checked={s.cwrControlled !== false}
                            onChange={e => setSplit(i,"cwrControlled",e.target.checked)}
                            style={{ accentColor:"#7c3aed", width:13, height:13, cursor:"pointer" }}
                          />
                          Controlled (SWR)
                        </label>
                      </div>
                    </div>
                  </div>
                ))}
                <button
                  onClick={() => setDraft(d => ({...d, splits:[...d.splits, {collabId:null,role:"Writer",writer:0,publisher:0,cwrDesignationCode:"CA",cwrControlled:true}]}))}
                  style={{ padding:"8px", borderRadius:6, border:"1px dashed var(--border)", background:"none", color:"var(--text-3)", fontSize:12, cursor:"pointer" }}
                >+ Add writer</button>
              </div>
            </>
          )}

          <div style={{ height:16 }}></div>
        </div>
      </div>
    </>
  );
}

// ─── Collaborator Drawer ──────────────────────────────────────────────────────

function CollabDrawer({ collab, onClose, onUpdate, onDelete, songs: songsProp, publishers: publishersProp, onAddPublisher, onSelectSong, isCentered, onToggleCenter }) {
  if (!collab) return null;
  const idx = COLLABS.findIndex(c => c.id === collab.id);
  const pal = COLLAB_PALETTE[Math.max(idx,0) % COLLAB_PALETTE.length];
  const pastProjects = (songsProp || SONGS).filter(s => s.splits.some(sp => sp.collabId === collab.id || sp.name === collab.name));
  const allPublishers = publishersProp || PUBLISHERS;

  const [editMode,    setEditMode]    = useState(false);
  const [confirmDel,  setConfirmDel]  = useState(false);
  const [form,        setForm]        = useState({});
  const [addingPub,   setAddingPub]   = useState(false);
  const [newPubForm,  setNewPubForm]  = useState({ name:"", type:"Indie" });

  const linkedPublisher = allPublishers.find(p => p.id === collab.publisherId);
  const editLinkedPublisher = form.publisherId ? allPublishers.find(p => p.id === form.publisherId) : null;

  const startEdit = () => {
    setForm({ ...collab, tags: (collab.tags||[]).join(", ") });
    setEditMode(true);
    setAddingPub(false);
  };
  const cancelEdit = () => { setEditMode(false); setAddingPub(false); };

  const handlePubSelectChange = (val) => {
    if (val === "__add__") { setAddingPub(true); return; }
    if (val === "self") {
      setForm(p => ({ ...p, publisherId: null, selfPublished: true, publishingEntity: "" }));
    } else if (val === "") {
      setForm(p => ({ ...p, publisherId: null, selfPublished: false, publishingEntity: "" }));
    } else {
      const pub = allPublishers.find(p => p.id === Number(val) || p.id === val);
      setForm(p => ({ ...p, publisherId: pub?.id || null, selfPublished: false, publishingEntity: pub?.name || "" }));
    }
    setAddingPub(false);
  };

  const handleCreatePublisher = () => {
    if (!newPubForm.name.trim()) return;
    const newPub = {
      id: Date.now(), name: newPubForm.name.trim(), type: newPubForm.type,
      email:"", phone:"", website:"", address:"", country:"", ipi:"", pro:"",
      roster:[], deals:[], controlled:false, notes:"", founded: String(new Date().getFullYear()),
      incomplete: true,
    };
    onAddPublisher(newPub);
    setForm(p => ({ ...p, publisherId: newPub.id, selfPublished: false, publishingEntity: newPub.name }));
    setAddingPub(false);
    setNewPubForm({ name:"", type:"Indie" });
  };

  const saveEdit = () => {
    const fn = (form.firstName || "").trim();
    const ln = (form.lastName  || "").trim();
    const updates = {
      ...form,
      tags: form.tags ? form.tags.split(",").map(t=>t.trim()).filter(Boolean) : [],
      defaultWriter: Number(form.defaultWriter)||0,
      defaultPublisher: Number(form.defaultPublisher)||0,
      ...(fn || ln ? { name: [fn, ln].filter(Boolean).join(" ") } : {}),
    };
    onUpdate(collab.id, updates);
    setEditMode(false);
  };

  const inp = (field, label, opts={}) => (
    <div style={{ marginBottom:10 }}>
      <div className="meta-label">{label}</div>
      {editMode
        ? <input value={form[field]||""} onChange={e=>setForm(p=>({...p,[field]:e.target.value}))}
            style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box", ...(opts.mono?{fontFamily:"monospace"}:{}) }} />
        : <div className={"meta-value"+(opts.mono?" mono":"")} style={{ fontSize:13 }}>{collab[field]||<span style={{color:"var(--text-3)"}}>—</span>}</div>
      }
    </div>
  );

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>
        <div className="drawer-header">
          <div style={{ display:"flex", alignItems:"center", gap:12 }}>
            <div style={{ width:44, height:44, borderRadius:12, background:pal.bg, color:pal.color, display:"flex", alignItems:"center", justifyContent:"center", fontWeight:700, fontSize:15, flexShrink:0 }}>
              {(editMode ? form.name : collab.name).split(" ").map(n=>n[0]).join("")}
            </div>
            <div>
              {editMode
                ? <input value={form.name||""} onChange={e=>setForm(p=>({...p,name:e.target.value}))} style={{ fontWeight:700, fontSize:16, border:"none", borderBottom:"1px solid var(--accent)", background:"none", color:"var(--text)", outline:"none", fontFamily:"var(--font)", width:"100%" }} />
                : <div className="drawer-title" style={{ fontSize:17 }}>{collab.name}</div>
              }
              <div style={{ fontSize:12, color:"var(--text-3)", marginTop:2 }}>{collab.role} · {collab.location}</div>
            </div>
          </div>
          <div style={{ display:"flex", gap:6, alignItems:"center" }}>
            {!editMode && !confirmDel && (
              <>
                <button onClick={startEdit} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Edit</button>
                <button onClick={()=>setConfirmDel(true)} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid #fca5a5", background:"#fff1f2", color:"#dc2626", cursor:"pointer", fontFamily:"var(--font)" }}>Delete</button>
              </>
            )}
            {editMode && (
              <>
                <button onClick={saveEdit} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"none", background:"var(--accent)", color:"#fff", cursor:"pointer", fontFamily:"var(--font)" }}>Save</button>
                <button onClick={cancelEdit} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Cancel</button>
              </>
            )}
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        {confirmDel && (
          <div style={{ margin:"12px 20px", padding:"12px 14px", background:"#fff1f2", border:"1px solid #fca5a5", borderRadius:8, display:"flex", justifyContent:"space-between", alignItems:"center", gap:12 }}>
            <div style={{ fontSize:13, color:"#7f1d1d" }}>Delete <strong>{collab.name}</strong>? This can't be undone.</div>
            <div style={{ display:"flex", gap:8, flexShrink:0 }}>
              <button onClick={()=>setConfirmDel(false)} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Cancel</button>
              <button onClick={()=>onDelete(collab.id)} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"none", background:"#dc2626", color:"#fff", cursor:"pointer", fontFamily:"var(--font)" }}>Delete</button>
            </div>
          </div>
        )}

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1, display:"flex", flexDirection:"column", gap:20 }}>

          {/* Status */}
          {editMode ? (
            <div style={{ display:"flex", gap:12, flexWrap:"wrap" }}>
              <div style={{ flex:1 }}>
                <div className="meta-label">Status</div>
                <select value={form.status||""} onChange={e=>setForm(p=>({...p,status:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}>
                  {["Active","Inactive","Pending"].map(s=><option key={s}>{s}</option>)}
                </select>
              </div>
              <div style={{ flex:1 }}>
                <div className="meta-label">Relationship</div>
                <input value={form.relationshipStatus||""} onChange={e=>setForm(p=>({...p,relationshipStatus:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }} />
              </div>
            </div>
          ) : (
            <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
              <StatusBadge status={collab.status} />
              <Badge color={pal.color} bg={pal.bg}>{collab.pro}</Badge>
              {(collab.tags||[]).map(t => <Badge key={t}>{t}</Badge>)}
            </div>
          )}

          {/* Contact */}
          <div>
            <div className="section-label">Contact</div>
            <div className="info-box" style={{ display:"flex", flexDirection:"column", gap:0 }}>
              {editMode ? (
                <div style={{ marginBottom:10 }}>
                  <div className="meta-label">Name (for CWR — split on first/last)</div>
                  <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:6 }}>
                    <input value={form.firstName||""} onChange={e=>setForm(p=>({...p,firstName:e.target.value}))}
                      placeholder="First" style={{ padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box" }} />
                    <input value={form.lastName||""} onChange={e=>setForm(p=>({...p,lastName:e.target.value}))}
                      placeholder="Last" style={{ padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box" }} />
                  </div>
                </div>
              ) : (
                <div style={{ marginBottom:10 }}>
                  <div className="meta-label">First / Last Name</div>
                  <div className="meta-value" style={{ fontSize:13 }}>
                    {collab.firstName || collab.lastName
                      ? <span>{collab.firstName||""} {collab.lastName||""}</span>
                      : <span style={{color:"var(--text-3)"}}>—</span>}
                  </div>
                </div>
              )}
              {inp("email",   "Email")}
              {inp("phone",   "Phone")}
              {inp("website", "Website")}
              {inp("location","Location")}
              {inp("company", "Company")}
            </div>
          </div>

          {/* Socials */}
          <div>
            <div className="section-label">Socials & Profiles</div>
            <div className="info-box">
              {inp("instagram", "Instagram")}
              {inp("spotify",   "Spotify")}
              {inp("manager",   "Manager")}
            </div>
          </div>

          {/* Publishing */}
          <div>
            <div className="section-label">Publishing & PRO</div>
            <div className="info-box">
              {inp("pro", "PRO Affiliation")}
              {inp("ipi", "IPI Number", {mono:true})}

              {/* Publisher link */}
              <div style={{ marginBottom:10 }}>
                <div className="meta-label">Publishing Entity</div>
                {editMode ? (
                  <>
                    <select
                      value={form.selfPublished ? "self" : (form.publisherId ? String(form.publisherId) : "")}
                      onChange={e => handlePubSelectChange(e.target.value)}
                      style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}
                    >
                      <option value="">— No publisher linked</option>
                      <option value="self">Self-Published</option>
                      {allPublishers.map(p => <option key={p.id} value={String(p.id)}>{p.name}{p.incomplete?" ⚠":""}</option>)}
                      <option value="__add__">+ Add Publisher…</option>
                    </select>
                    {addingPub && (
                      <div style={{ marginTop:8, padding:"10px 12px", background:"var(--bg-2)", border:"1px solid var(--border)", borderRadius:7, display:"flex", flexDirection:"column", gap:8 }}>
                        <div style={{ fontSize:12, fontWeight:600, color:"var(--text-2)" }}>New Publisher</div>
                        <input
                          placeholder="Publisher name"
                          value={newPubForm.name}
                          onChange={e=>setNewPubForm(p=>({...p,name:e.target.value}))}
                          style={{ padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--card)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}
                        />
                        <select
                          value={newPubForm.type}
                          onChange={e=>setNewPubForm(p=>({...p,type:e.target.value}))}
                          style={{ padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--card)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}
                        >
                          {["Indie","Major","Self-Published","Admin"].map(t=><option key={t}>{t}</option>)}
                        </select>
                        <div style={{ display:"flex", gap:6 }}>
                          <button onClick={handleCreatePublisher} style={{ flex:1, padding:"5px 0", borderRadius:6, border:"none", background:"var(--accent)", color:"#fff", fontSize:12, cursor:"pointer", fontFamily:"var(--font)" }}>Create & Link</button>
                          <button onClick={()=>setAddingPub(false)} style={{ padding:"5px 10px", borderRadius:6, border:"1px solid var(--border)", background:"none", color:"var(--text-2)", fontSize:12, cursor:"pointer", fontFamily:"var(--font)" }}>Cancel</button>
                        </div>
                      </div>
                    )}
                  </>
                ) : (
                  <div className="meta-value" style={{ fontSize:13 }}>
                    {collab.selfPublished
                      ? "Self-Published"
                      : linkedPublisher
                        ? <span>{linkedPublisher.name}{linkedPublisher.incomplete && <span style={{ marginLeft:5, fontSize:9.5, color:"#d97706", background:"#fef3c7", border:"1px solid #fcd34d", borderRadius:4, padding:"1px 5px" }}>⚠ Incomplete</span>}</span>
                        : <span style={{color:"var(--text-3)"}}>—</span>
                    }
                  </div>
                )}
              </div>
              {editMode ? (
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
                  <div>
                    <div className="meta-label">Default Writer %</div>
                    <input type="number" min="0" max="100" value={form.defaultWriter||0} onChange={e=>setForm(p=>({...p,defaultWriter:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"monospace", boxSizing:"border-box" }} />
                  </div>
                  <div>
                    <div className="meta-label">Default Publisher %</div>
                    <input type="number" min="0" max="100" value={form.defaultPublisher||0} onChange={e=>setForm(p=>({...p,defaultPublisher:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"monospace", boxSizing:"border-box" }} />
                  </div>
                </div>
              ) : (
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12, marginTop:4 }}>
                  <div>
                    <div className="meta-label">Default Writer %</div>
                    <div className="mono meta-value" style={{ color:SPLIT_COLORS[Math.max(idx,0)%SPLIT_COLORS.length] }}>{collab.defaultWriter}%</div>
                  </div>
                  <div>
                    <div className="meta-label">Default Publisher %</div>
                    <div className="mono meta-value">{collab.defaultPublisher}%</div>
                  </div>
                </div>
              )}
              {editMode && (
                <div style={{ marginTop:8 }}>
                  <div className="meta-label">Tags (comma-separated)</div>
                  <input value={form.tags||""} onChange={e=>setForm(p=>({...p,tags:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box" }} />
                </div>
              )}
            </div>
          </div>

          {/* Past projects */}
          {pastProjects.length > 0 && (
            <div>
              <div className="section-label">Collaborations ({pastProjects.length})</div>
              <div style={{ display:"flex", flexDirection:"column", gap:6 }}>
                {pastProjects.map(s => {
                  const sp = s.splits.find(x => x.collabId === collab.id || x.name === collab.name);
                  return (
                    <div key={s.id} className="info-box" onClick={() => onSelectSong && onSelectSong(s)} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"10px 12px", cursor: onSelectSong ? "pointer" : "default" }}>
                      <div>
                        <div style={{ fontWeight:500, fontSize:13 }}>{s.title}</div>
                        <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{s.genre} · {s.status}</div>
                      </div>
                      {sp && <span className="mono" style={{ fontSize:13, fontWeight:700, color:SPLIT_COLORS[0] }}>{sp.writer}%</span>}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Notes */}
          <div>
            <div className="section-label">Notes</div>
            {editMode
              ? <textarea value={form.notes||""} onChange={e=>setForm(p=>({...p,notes:e.target.value}))} rows={4} style={{ width:"100%", padding:"8px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", resize:"vertical", boxSizing:"border-box" }} />
              : <div className="info-box" style={{ fontSize:13, lineHeight:1.65, color:"var(--text-2)" }}>{collab.notes}</div>
            }
          </div>

          <div style={{ height:8 }}></div>
        </div>
      </div>
    </>
  );
}

// ─── Tweaks Panel ─────────────────────────────────────────────────────────────

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentColor": "#7c6fff",
  "showAnalytics": true,
  "density": "comfortable"
}/*EDITMODE-END*/;

function TweaksPanel({ tweaks, setTweaks, visible, onClose }) {
  if (!visible) return null;
  const accents = [
    {label:"Violet", v:"#7c6fff"}, {label:"Indigo", v:"#4f46e5"},
    {label:"Rose",   v:"#e11d48"}, {label:"Teal",   v:"#0d9488"},
    {label:"Amber",  v:"#d97706"},
  ];
  const update = (key, val) => {
    const next = {...tweaks, [key]: val};
    setTweaks(next);
    window.parent.postMessage({ type:"__edit_mode_set_keys", edits:{ [key]: val } }, "*");
    if (key === "accentColor") document.documentElement.style.setProperty("--accent", val);
  };
  return (
    <div style={{
      position:"fixed", bottom:24, right:24, zIndex:9999,
      background:"#fff", border:"1px solid var(--border)",
      borderRadius:12, padding:"18px 20px", width:256,
      boxShadow:"0 8px 32px rgba(0,0,0,0.12)",
      fontFamily:"var(--font)"
    }}>
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:18 }}>
        <span style={{ fontWeight:600, fontSize:14, color:"var(--text)" }}>Tweaks</span>
        <button onClick={onClose} style={{ background:"none", border:"none", color:"var(--text-3)", cursor:"pointer", fontSize:14 }}>✕</button>
      </div>
      <div style={{ marginBottom:18 }}>
        <div className="tweak-label">Accent Color</div>
        <div style={{ display:"flex", gap:8 }}>
          {accents.map(a => (
            <button key={a.v} onClick={() => update("accentColor", a.v)} title={a.label} style={{
              width:28, height:28, borderRadius:"50%", background:a.v, cursor:"pointer",
              border: tweaks.accentColor===a.v ? "3px solid #fff" : "3px solid transparent",
              boxShadow: tweaks.accentColor===a.v ? "0 0 0 2px " + a.v : "none",
              transition:"box-shadow 0.15s",
            }}></button>
          ))}
        </div>
      </div>
      <div style={{ marginBottom:18 }}>
        <div className="tweak-label">Analytics Widgets</div>
        <button onClick={() => update("showAnalytics", !tweaks.showAnalytics)} style={{
          width:"100%", padding:"7px 12px", borderRadius:7, fontSize:12.5, fontWeight:500,
          background: tweaks.showAnalytics ? "var(--accent)" : "var(--bg-2)",
          color: tweaks.showAnalytics ? "#fff" : "var(--text-3)",
          border:"1px solid " + (tweaks.showAnalytics ? "var(--accent)" : "var(--border)"),
          cursor:"pointer", transition:"all 0.15s"
        }}>{tweaks.showAnalytics ? "Visible" : "Hidden"}</button>
      </div>
      <div>
        <div className="tweak-label">Row Density</div>
        <div style={{ display:"flex", gap:6 }}>
          {["compact","comfortable","spacious"].map(d => (
            <button key={d} onClick={() => update("density", d)} style={{
              flex:1, padding:"5px 4px", borderRadius:6, fontSize:11, fontWeight:500,
              background: tweaks.density===d ? "var(--accent)" : "var(--bg-2)",
              color: tweaks.density===d ? "#fff" : "var(--text-3)",
              border:"1px solid " + (tweaks.density===d ? "var(--accent)" : "var(--border)"),
              cursor:"pointer", textTransform:"capitalize", transition:"all 0.15s"
            }}>{d}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Publisher Drawer ─────────────────────────────────────────────────────────

const PUB_TYPE_COLORS = {
  "Major":         { bg:"#dbeafe", color:"#1d4ed8" },
  "Indie":         { bg:"#ede9fe", color:"#5b21b6" },
  "Self-Published":{ bg:"#dcfce7", color:"#166534" },
  "Admin":         { bg:"#fef3c7", color:"#92400e" },
};

function PublisherDrawer({ publisher, publishers: publishersProp, collabs: collabsProp, songs: songsProp, onClose, onUpdate, onUpdateCollab, onDelete, isCentered, onToggleCenter }) {
  if (!publisher) return null;
  const tc = PUB_TYPE_COLORS[publisher.type] || { bg:"#f3f4f6", color:"#6b7280" };
  const allCollabs    = collabsProp    || COLLABS;
  const allSongs      = songsProp      || SONGS;
  const allPublishers = (publishersProp || PUBLISHERS).filter(p => p.id !== publisher.id);
  const rosterCollabs = allCollabs.filter(c => (publisher.roster||[]).includes(c.id));
  const pubSongs = allSongs.filter(s =>
    s.publishingOwner === publisher.name ||
    s.splits.some(sp => rosterCollabs.some(c => c.id === sp.collabId || c.name === sp.name))
  );

  const [editMode,      setEditMode]      = useState(false);
  const [confirmDel,    setConfirmDel]    = useState(false);
  const [form,          setForm]          = useState({});
  const [collabSearch,  setCollabSearch]  = useState("");
  const [showAddCollab, setShowAddCollab] = useState(false);

  const startEdit = () => {
    setForm({ ...publisher, deals: (publisher.deals||[]).join(", ") });
    setEditMode(true);
  };
  const cancelEdit = () => setEditMode(false);
  const saveEdit = () => {
    const updates = { ...form, deals: form.deals ? form.deals.split(",").map(d=>d.trim()).filter(Boolean) : [] };
    onUpdate(publisher.id, updates);
    setEditMode(false);
  };

  const inp = (field, label, opts={}) => (
    <div style={{ marginBottom:10 }}>
      <div className="meta-label">{label}</div>
      {editMode
        ? <input value={form[field]||""} onChange={e=>setForm(p=>({...p,[field]:e.target.value}))}
            style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:opts.mono?"monospace":"var(--font)", boxSizing:"border-box" }} />
        : <div style={{ fontSize:13, fontWeight:500, color:"var(--text)" }}>{publisher[field]||<span style={{color:"var(--text-3)"}}>—</span>}</div>
      }
    </div>
  );

  const assignCollab = (collab) => {
    if (!onUpdateCollab) return;
    onUpdateCollab(collab.id, { publisherId: publisher.id, selfPublished: false, publishingEntity: publisher.name });
    setCollabSearch(""); setShowAddCollab(false);
  };

  const unassignCollab = (collab) => {
    if (!onUpdateCollab) return;
    onUpdateCollab(collab.id, { publisherId: null, selfPublished: false, publishingEntity: "" });
  };

  const availableCollabs = allCollabs.filter(c =>
    !(publisher.roster||[]).includes(c.id) &&
    c.name.toLowerCase().includes(collabSearch.toLowerCase())
  ).slice(0, 8);

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>
        <div className="drawer-header">
          <div>
            {editMode
              ? <input value={form.name||""} onChange={e=>setForm(p=>({...p,name:e.target.value}))} style={{ fontWeight:700, fontSize:16, border:"none", borderBottom:"1px solid var(--accent)", background:"none", color:"var(--text)", outline:"none", fontFamily:"var(--font)", width:"100%" }} />
              : <div className="drawer-title">{publisher.name}</div>
            }
            <div style={{ fontSize:12, color:"var(--text-3)", marginTop:2 }}>Est. {publisher.founded} · {publisher.country}</div>
          </div>
          <div style={{ display:"flex", gap:6, alignItems:"center" }}>
            {!editMode && !confirmDel && (
              <>
                <button onClick={startEdit} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Edit</button>
                <button onClick={()=>setConfirmDel(true)} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid #fca5a5", background:"#fff1f2", color:"#dc2626", cursor:"pointer", fontFamily:"var(--font)" }}>Delete</button>
              </>
            )}
            {editMode && (
              <>
                <button onClick={saveEdit} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"none", background:"var(--accent)", color:"#fff", cursor:"pointer", fontFamily:"var(--font)" }}>Save</button>
                <button onClick={cancelEdit} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Cancel</button>
              </>
            )}
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        {confirmDel && (
          <div style={{ margin:"12px 20px", padding:"12px 14px", background:"#fff1f2", border:"1px solid #fca5a5", borderRadius:8, display:"flex", justifyContent:"space-between", alignItems:"center", gap:12 }}>
            <div style={{ fontSize:13, color:"#7f1d1d" }}>Delete <strong>{publisher.name}</strong>? This can't be undone.</div>
            <div style={{ display:"flex", gap:8, flexShrink:0 }}>
              <button onClick={()=>setConfirmDel(false)} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Cancel</button>
              <button onClick={()=>onDelete(publisher.id)} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"none", background:"#dc2626", color:"#fff", cursor:"pointer", fontFamily:"var(--font)" }}>Delete</button>
            </div>
          </div>
        )}

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1, display:"flex", flexDirection:"column", gap:18 }}>

          {/* Type + deals */}
          {editMode ? (
            <div style={{ display:"flex", gap:12 }}>
              <div style={{ flex:1 }}>
                <div className="meta-label">Type</div>
                <select value={form.type||""} onChange={e=>setForm(p=>({...p,type:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}>
                  {["Indie","Major","Self-Published","Admin"].map(t=><option key={t}>{t}</option>)}
                </select>
              </div>
              <div style={{ flex:1 }}>
                <div className="meta-label">Deals (comma-separated)</div>
                <input value={form.deals||""} onChange={e=>setForm(p=>({...p,deals:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box" }} />
              </div>
            </div>
          ) : (
            <div style={{ display:"flex", gap:6, flexWrap:"wrap" }}>
              <Badge color={tc.color} bg={tc.bg}>{publisher.type}</Badge>
              <Badge>{publisher.pro}</Badge>
              {(publisher.deals||[]).map(d => <Badge key={d}>{d}</Badge>)}
            </div>
          )}

          {/* Contact */}
          <div>
            <div className="section-label">Contact</div>
            <div className="info-box" style={{ display:"flex", flexDirection:"column", gap:0 }}>
              {inp("email",   "Email")}
              {inp("phone",   "Phone")}
              {inp("website", "Website")}
              {inp("address", "Address")}
              {inp("country", "Country")}
            </div>
          </div>

          {/* Publishing details */}
          <div>
            <div className="section-label">Publishing Details</div>
            <div className="info-box">
              <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
                <div>
                  <div className="meta-label">PRO</div>
                  {editMode
                    ? <input value={form.pro||""} onChange={e=>setForm(p=>({...p,pro:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box" }} />
                    : <div style={{ fontSize:13, fontWeight:500 }}>{publisher.pro}</div>
                  }
                </div>
                <div>
                  <div className="meta-label">IPI Number</div>
                  {editMode
                    ? <input value={form.ipi||""} onChange={e=>setForm(p=>({...p,ipi:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"monospace", boxSizing:"border-box" }} />
                    : <div className="mono" style={{ fontSize:12, fontWeight:500 }}>{publisher.ipi}</div>
                  }
                </div>
              </div>
              {editMode && (
                <div style={{ marginTop:8 }}>
                  <div className="meta-label">Founded</div>
                  <input value={form.founded||""} onChange={e=>setForm(p=>({...p,founded:e.target.value}))} style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", boxSizing:"border-box" }} />
                </div>
              )}

              {/* CWR publisher type */}
              <div style={{ marginTop:10, paddingTop:10, borderTop:"1px solid var(--border-sub)" }}>
                <div className="meta-label" style={{ marginBottom:4 }}>CWR Publisher Type</div>
                {editMode ? (
                  <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
                    <select value={form.publisherType||"E"} onChange={e=>setForm(p=>({...p,publisherType:e.target.value,parentPublisherId:e.target.value==="E"?null:p.parentPublisherId}))}
                      style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}>
                      <option value="E">E — Original Publisher</option>
                      <option value="SE">SE — Sub-Publisher</option>
                      <option value="AM">AM — Administrator</option>
                    </select>
                    {(form.publisherType === "SE" || form.publisherType === "AM") && (
                      <div>
                        <div className="meta-label">Parent Publisher</div>
                        <select value={form.parentPublisherId||""} onChange={e=>setForm(p=>({...p,parentPublisherId:e.target.value?Number(e.target.value):null}))}
                          style={{ width:"100%", padding:"5px 8px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)" }}>
                          <option value="">— select parent —</option>
                          {allPublishers.filter(p=>!p.publisherType||p.publisherType==="E").map(p=>(
                            <option key={p.id} value={p.id}>{p.name}</option>
                          ))}
                        </select>
                      </div>
                    )}
                  </div>
                ) : (
                  <div style={{ fontSize:13, fontWeight:500, color:"var(--text)" }}>
                    {publisher.publisherType === "SE" ? "SE — Sub-Publisher" : publisher.publisherType === "AM" ? "AM — Administrator" : "E — Original Publisher"}
                    {(publisher.publisherType === "SE" || publisher.publisherType === "AM") && publisher.parentPublisherId && (() => {
                      const parent = (publishersProp || PUBLISHERS).find(p => p.id === publisher.parentPublisherId);
                      return parent ? <span style={{ color:"var(--text-3)", fontWeight:400 }}> under {parent.name}</span> : null;
                    })()}
                  </div>
                )}
              </div>

              {/* Collection territories */}
              <div style={{ marginTop:10 }}>
                <div className="meta-label" style={{ marginBottom:4 }}>Collection Territories (CWR)</div>
                {editMode ? (
                  <div>
                    {(form.collectionTerritories || []).map((t, i) => (
                      <div key={i} style={{ display:"flex", gap:6, alignItems:"center", marginBottom:5 }}>
                        <select value={t.code} onChange={e=>setForm(p=>({...p,collectionTerritories:p.collectionTerritories.map((x,j)=>j===i?{...x,code:e.target.value}:x)}))}
                          style={{ flex:2, padding:"4px 6px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:11.5, fontFamily:"var(--font)" }}>
                          {(typeof CWR_TERRITORIES !== "undefined" ? CWR_TERRITORIES : []).map(terr=>(
                            <option key={terr.code} value={terr.code}>{terr.name} ({terr.code})</option>
                          ))}
                        </select>
                        <select value={t.mode} onChange={e=>setForm(p=>({...p,collectionTerritories:p.collectionTerritories.map((x,j)=>j===i?{...x,mode:e.target.value}:x)}))}
                          style={{ flex:1, padding:"4px 6px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:11.5, fontFamily:"var(--font)" }}>
                          <option value="include">Include</option>
                          <option value="exclude">Exclude</option>
                        </select>
                        <button onClick={()=>setForm(p=>({...p,collectionTerritories:p.collectionTerritories.filter((_,j)=>j!==i)}))}
                          style={{ width:22, height:22, borderRadius:4, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-3)", fontSize:11, cursor:"pointer", flexShrink:0, display:"flex", alignItems:"center", justifyContent:"center" }}>✕</button>
                      </div>
                    ))}
                    <button onClick={()=>setForm(p=>({...p,collectionTerritories:[...(p.collectionTerritories||[]),{code:"2136",mode:"include"}]}))}
                      style={{ fontSize:11, padding:"3px 9px", borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)", marginTop:2 }}>+ Add Territory</button>
                    <div style={{ fontSize:10.5, color:"var(--text-3)", marginTop:5, lineHeight:1.5 }}>
                      Leave empty to default to World (2136). For World excluding AU: add World (include) + Australia (exclude).
                    </div>
                  </div>
                ) : (
                  <div style={{ fontSize:12, color:"var(--text-2)" }}>
                    {(publisher.collectionTerritories || []).length === 0
                      ? <span style={{ color:"var(--text-3)" }}>World (default)</span>
                      : (publisher.collectionTerritories || []).map((t, i) => {
                          const terrDef = (typeof CWR_TERRITORIES !== "undefined" ? CWR_TERRITORIES : []).find(x => x.code === t.code);
                          return <span key={i} style={{ marginRight:8 }}>{t.mode === "exclude" ? "−" : "+"}{terrDef ? terrDef.name : t.code}</span>;
                        })
                    }
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Artist roster */}
          <div>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:7 }}>
              <div className="section-label" style={{ margin:0 }}>Artist Roster ({rosterCollabs.length})</div>
              {onUpdateCollab && (
                <button onClick={() => { setShowAddCollab(s => !s); setCollabSearch(""); }}
                  style={{ fontSize:11, padding:"2px 9px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>
                  {showAddCollab ? "Cancel" : "+ Add"}
                </button>
              )}
            </div>

            {showAddCollab && (
              <div style={{ marginBottom:10, position:"relative" }}>
                <input
                  value={collabSearch}
                  onChange={e => setCollabSearch(e.target.value)}
                  placeholder="Search collaborators…"
                  autoFocus
                  style={{ width:"100%", padding:"6px 10px", borderRadius:6, border:"1px solid var(--accent)", background:"var(--bg)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", outline:"none", boxSizing:"border-box" }}
                />
                {availableCollabs.length > 0 && (
                  <div style={{ position:"absolute", top:"100%", left:0, right:0, background:"var(--card)", border:"1px solid var(--border)", borderRadius:8, boxShadow:"var(--shadow)", zIndex:10, overflow:"hidden", marginTop:2 }}>
                    {availableCollabs.map(c => (
                      <div key={c.id} onClick={() => assignCollab(c)}
                        style={{ display:"flex", alignItems:"center", gap:10, padding:"8px 12px", cursor:"pointer", fontSize:13, borderBottom:"1px solid var(--border-sub)" }}
                        onMouseEnter={e => e.currentTarget.style.background="var(--bg-2)"}
                        onMouseLeave={e => e.currentTarget.style.background=""}
                      >
                        <span style={{ fontWeight:500 }}>{c.name}</span>
                        <span style={{ fontSize:11, color:"var(--text-3)" }}>{c.role}</span>
                      </div>
                    ))}
                  </div>
                )}
                {availableCollabs.length === 0 && collabSearch && (
                  <div style={{ padding:"8px 10px", fontSize:12, color:"var(--text-3)" }}>No collaborators found</div>
                )}
              </div>
            )}

            {rosterCollabs.length === 0 && !showAddCollab && (
              <div style={{ fontSize:13, color:"var(--text-3)", padding:"10px 0" }}>No collaborators linked yet.</div>
            )}
            <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
              {rosterCollabs.map(c => {
                const cidx = allCollabs.findIndex(x => x.id === c.id);
                const pal  = COLLAB_PALETTE[Math.max(cidx,0) % COLLAB_PALETTE.length];
                const cSongs = allSongs.filter(s => s.splits.some(sp => sp.collabId === c.id || sp.name === c.name));
                return (
                  <div key={c.id} className="info-box" style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 12px" }}>
                    <div style={{ width:36, height:36, borderRadius:9, background:pal.bg, color:pal.color, display:"flex", alignItems:"center", justifyContent:"center", fontWeight:700, fontSize:13, flexShrink:0 }}>
                      {c.name.split(" ").map(n => n[0]).join("")}
                    </div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontWeight:500, fontSize:13 }}>{c.name}</div>
                      <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{c.role} · {c.pro}</div>
                    </div>
                    <div style={{ textAlign:"right", display:"flex", alignItems:"center", gap:8, flexShrink:0 }}>
                      <div>
                        <div style={{ fontSize:12, fontWeight:600, color:"var(--accent)" }}>{cSongs.length} song{cSongs.length !== 1 ? "s" : ""}</div>
                        <StatusBadge status={c.status} />
                      </div>
                      {onUpdateCollab && (
                        <button onClick={() => unassignCollab(c)} title="Remove from roster"
                          style={{ width:22, height:22, borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-3)", fontSize:11, cursor:"pointer", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>✕</button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Song catalog */}
          {pubSongs.length > 0 && (
            <div>
              <div className="section-label">Catalog ({pubSongs.length} songs)</div>
              <div style={{ display:"flex", flexDirection:"column", gap:6 }}>
                {pubSongs.map(s => (
                  <div key={s.id} className="info-box" style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"9px 12px" }}>
                    <div>
                      <div style={{ fontWeight:500, fontSize:13 }}>{s.title}</div>
                      <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{s.genre} · {s.status}</div>
                    </div>
                    <StatusBadge status={s.status} />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Notes */}
          <div>
            <div className="section-label">Notes</div>
            {editMode
              ? <textarea value={form.notes||""} onChange={e=>setForm(p=>({...p,notes:e.target.value}))} rows={4} style={{ width:"100%", padding:"8px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", resize:"vertical", boxSizing:"border-box" }} />
              : <div className="info-box" style={{ fontSize:13, lineHeight:1.65, color:"var(--text-2)" }}>{publisher.notes}</div>
            }
          </div>

          <div style={{ height:8 }}></div>
        </div>
      </div>
    </>
  );
}

// ─── Command Palette ──────────────────────────────────────────────────────────

const PALETTE_PAGES = [
  {id:"dashboard",label:"Dashboard",type:"page"},{id:"songs",label:"Songs",type:"page"},
  {id:"splits",label:"Splits & Rights",type:"page"},{id:"collaborators",label:"Collaborators",type:"page"},
  {id:"publishers",label:"Publishers",type:"page"},{id:"sync",label:"Sync Licensing",type:"page"},
  {id:"releases",label:"Releases",type:"page"},{id:"analytics",label:"Analytics",type:"page"},
];
const TYPE_ICON  = { page:"→", song:"♪", collab:"◎", publisher:"◈" };
const TYPE_LABEL = { page:"Page", song:"Song", collab:"Collaborator", publisher:"Publisher" };

function CommandPalette({ songs, onNavigate, onSelectSong, onClose }) {
  const [query,     setQuery]     = useState("");
  const [activeIdx, setActiveIdx] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  const results = useMemo(() => {
    if (!query.trim()) return [];
    const q = query.toLowerCase();
    const pages   = PALETTE_PAGES.filter(p => p.label.toLowerCase().includes(q));
    const songRes = songs.filter(s => s.title.toLowerCase().includes(q)||s.genre.toLowerCase().includes(q)||s.isrc.toLowerCase().includes(q)).slice(0,4).map(s=>({...s,type:"song"}));
    const colRes  = COLLABS.filter(c => c.name.toLowerCase().includes(q)||c.role.toLowerCase().includes(q)).slice(0,3).map(c=>({...c,type:"collab"}));
    const pubRes  = PUBLISHERS.filter(p => p.name.toLowerCase().includes(q)).slice(0,2).map(p=>({...p,type:"publisher"}));
    return [...pages, ...songRes, ...colRes, ...pubRes];
  }, [query, songs]);

  const handleSelect = (item) => {
    if (item.type==="page")  { onNavigate(item.id); }
    if (item.type==="song")  { onNavigate("songs"); onSelectSong(item); }
    if (item.type==="collab"||item.type==="publisher") { onNavigate(item.type==="collab"?"collaborators":"publishers"); }
    onClose();
  };

  const onKeyDown = (e) => {
    if (e.key==="ArrowDown") { e.preventDefault(); setActiveIdx(i=>Math.min(i+1,results.length-1)); }
    if (e.key==="ArrowUp")   { e.preventDefault(); setActiveIdx(i=>Math.max(i-1,0)); }
    if (e.key==="Enter" && results[activeIdx]) handleSelect(results[activeIdx]);
    if (e.key==="Escape") onClose();
  };

  return (
    <>
      <div style={{ position:"fixed", inset:0, background:"rgba(0,0,0,0.3)", zIndex:500, backdropFilter:"blur(2px)" }} onClick={onClose}></div>
      <div style={{ position:"fixed", top:"15%", left:"50%", transform:"translateX(-50%)", width:560, background:"var(--card)", border:"1px solid var(--border)", borderRadius:12, boxShadow:"0 20px 60px rgba(0,0,0,0.15)", zIndex:501, overflow:"hidden", animation:"pageFade 0.12s ease" }}>
        <div style={{ display:"flex", alignItems:"center", gap:10, padding:"13px 16px", borderBottom:"1px solid var(--border)" }}>
          <span style={{ fontSize:16, color:"var(--text-3)" }}>⌕</span>
          <input ref={inputRef} value={query} onChange={e=>{setQuery(e.target.value);setActiveIdx(0);}} onKeyDown={onKeyDown}
            placeholder="Search pages, songs, collaborators, publishers…"
            style={{ flex:1, border:"none", outline:"none", fontSize:15, background:"none", color:"var(--text)", fontFamily:"var(--font)" }} />
          {query && <button onClick={()=>setQuery("")} style={{ background:"none", border:"none", color:"var(--text-3)", cursor:"pointer", fontSize:12 }}>✕</button>}
          <kbd style={{ fontSize:11, background:"var(--bg-2)", border:"1px solid var(--border)", borderRadius:4, padding:"2px 6px", color:"var(--text-3)" }}>ESC</kbd>
        </div>
        <div style={{ maxHeight:360, overflowY:"auto" }}>
          {query.trim()==="" ? (
            <div>
              <div style={{ padding:"10px 16px 4px", fontSize:10, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.08em" }}>Recent Songs</div>
              {[...songs].reverse().slice(0,3).map(s => (
                <div key={s.id} onClick={()=>handleSelect({...s,type:"song"})} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 16px", cursor:"pointer", transition:"background 0.08s" }}
                  onMouseEnter={e=>e.currentTarget.style.background="var(--bg-2)"} onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                  <span style={{ color:"var(--text-3)", fontSize:14 }}>♪</span>
                  <div><div style={{ fontSize:13, fontWeight:500 }}>{s.title}</div><div style={{ fontSize:11, color:"var(--text-3)" }}>{s.genre} · {s.status}</div></div>
                </div>
              ))}
              <div style={{ padding:"10px 16px 4px", fontSize:10, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.08em", borderTop:"1px solid var(--border)" }}>Pages</div>
              {PALETTE_PAGES.map(p => (
                <div key={p.id} onClick={()=>handleSelect(p)} style={{ display:"flex", alignItems:"center", gap:12, padding:"8px 16px", cursor:"pointer", transition:"background 0.08s" }}
                  onMouseEnter={e=>e.currentTarget.style.background="var(--bg-2)"} onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                  <span style={{ color:"var(--text-3)" }}>→</span>
                  <span style={{ fontSize:13 }}>{p.label}</span>
                </div>
              ))}
            </div>
          ) : results.length===0 ? (
            <div style={{ padding:32, textAlign:"center", color:"var(--text-3)", fontSize:13 }}>No results for "{query}"</div>
          ) : results.map((item, i) => (
            <div key={i} onClick={()=>handleSelect(item)} onMouseEnter={()=>setActiveIdx(i)}
              style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 16px", cursor:"pointer",
                background: i===activeIdx ? "var(--accent-dim)" : "transparent", transition:"background 0.08s" }}>
              <span style={{ color: i===activeIdx?"var(--accent)":"var(--text-3)", fontSize:13, minWidth:16 }}>{TYPE_ICON[item.type]}</span>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:500 }}>{item.title||item.name||item.label}</div>
                {item.genre && <div style={{ fontSize:11, color:"var(--text-3)" }}>{item.genre}</div>}
                {item.role  && <div style={{ fontSize:11, color:"var(--text-3)" }}>{item.role}</div>}
              </div>
              <span style={{ fontSize:10, color:"var(--text-3)", background:"var(--bg-2)", padding:"2px 7px", borderRadius:4 }}>{TYPE_LABEL[item.type]}</span>
            </div>
          ))}
        </div>
        <div style={{ padding:"8px 16px", borderTop:"1px solid var(--border)", display:"flex", gap:16, fontSize:11, color:"var(--text-3)" }}>
          <span>↑↓ Navigate</span><span>↵ Select</span><span>Esc Close</span>
          <span style={{ marginLeft:"auto" }}>⌘K to open</span>
        </div>
      </div>
    </>
  );
}

// ─── New Song Modal ───────────────────────────────────────────────────────────

const KEY_OPTIONS  = ["C Major","C Minor","C# Major","C# Minor","D Major","D Minor","Eb Major","Eb Minor","E Major","E Minor","F Major","F Minor","F# Major","F# Minor","G Major","G Minor","Ab Major","Ab Minor","A Major","A Minor","Bb Major","Bb Minor","B Major","B Minor"];
const GENRE_OPTIONS = ["Pop","Electronic / Pop","Pop / Soul","R&B / Soul","Synth-Pop","Ambient / Electronic","Indie / Rock","Alternative","Hip-Hop","Country","Classical","Jazz"];
const STATUS_OPTIONS = ["Demo","In Progress","Mixing","Mastered","Released"];
const MOOD_OPTIONS   = ["Dark","Warm","Uplifting","Energetic","Cinematic","Nostalgic","Emotional","Peaceful","Intense","Intimate","Atmospheric","Motivational","Ethereal","Raw","Melancholic","Brooding","Hypnotic","Futuristic","Cosmic","Gritty"];

function NewSongModal({ onClose, onSave, collabs: collabsProp, artists: artistsProp, onNewCollab, onNewArtist }) {
  const collabs = collabsProp || COLLABS;
  const artists = artistsProp || ARTISTS;
  const camCollab = collabs.find(c => c.name === "Cameron Taylor");
  const [form, setForm] = useState({
    title:"", version:"Original", isrc:"", iswc:"", bpm:120, key:"C Major",
    genre:"Pop", duration:"", status:"Demo", syncReady:false, stemsAvailable:false,
    instrumental:false, releaseDate:"", masterOwner:"Cameron Taylor",
    publishingOwner:"Vault Music Publishing", ownershipPct:100, pro:"APRA AMCOS",
    moods:[], notes:"", artistId:null, artist:"",
    splits:[{ collabId: camCollab ? camCollab.id : null, role:"Writer / Producer", writer:100, publisher:100 }]
  });

  const set   = (k,v) => setForm(f => ({...f, [k]:v}));
  const total = form.splits.reduce((a,s) => a + Number(s.writer||0), 0);
  const splitsOk = Math.abs(total - 100) < 0.01;

  const addSplit    = () => set("splits",[...form.splits,{collabId:null,role:"Co-Writer",writer:0,publisher:0}]);
  const removeSplit = (i) => set("splits",form.splits.filter((_,j)=>j!==i));
  const updateSplit = (i,k,v) => set("splits",form.splits.map((s,j)=>j===i?{...s,[k]:k==="writer"||k==="publisher"?Number(v):v}:s));
  const toggleMood  = (m) => set("moods",form.moods.includes(m)?form.moods.filter(x=>x!==m):[...form.moods,m]);

  const iStyle = { width:"100%", padding:"7px 10px", border:"1px solid var(--border)", borderRadius:6, background:"var(--bg-2)", color:"var(--text)", fontSize:13, fontFamily:"var(--font)", outline:"none" };
  const FInput = ({label,mono,...p}) => (
    <div><div className="meta-label" style={{marginBottom:5}}>{label}</div>
    <input {...p} style={{...iStyle,...(mono?{fontFamily:"var(--mono)"}:{}), ...(p.style||{})}}
      onFocus={e=>e.target.style.borderColor="var(--accent)"} onBlur={e=>e.target.style.borderColor="var(--border)"}/></div>
  );
  const FSelect = ({label,options,...p}) => (
    <div><div className="meta-label" style={{marginBottom:5}}>{label}</div>
    <select {...p} style={{...iStyle}}>{options.map(o=><option key={o}>{o}</option>)}</select></div>
  );
  const Toggle = ({label,value,onChange}) => (
    <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
      <span style={{fontSize:13,color:"var(--text-2)"}}>{label}</span>
      <button onClick={()=>onChange(!value)} style={{width:38,height:22,borderRadius:11,border:"none",cursor:"pointer",background:value?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.15s"}}>
        <div style={{position:"absolute",top:3,left:value?18:3,width:16,height:16,borderRadius:"50%",background:"#fff",transition:"left 0.15s"}}></div>
      </button>
    </div>
  );

  const handleSave = () => {
    if (!form.title.trim()||!splitsOk) return;
    onSave({...form, id:Date.now(), artworkHue:Math.floor(Math.random()*360), bpm:Number(form.bpm), ownershipPct:Number(form.ownershipPct)});
    onClose();
  };

  return (
    <>
      <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,0.28)",zIndex:400,backdropFilter:"blur(2px)"}} onClick={onClose}></div>
      <div style={{position:"fixed",top:"4%",left:"50%",transform:"translateX(-50%)",width:640,maxHeight:"92vh",background:"var(--card)",border:"1px solid var(--border)",borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.14)",zIndex:401,display:"flex",flexDirection:"column",overflow:"hidden",animation:"pageFade 0.15s ease"}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"16px 20px",borderBottom:"1px solid var(--border)"}}>
          <div style={{fontWeight:700,fontSize:16}}>New Song</div>
          <button className="icon-btn" onClick={onClose}>✕</button>
        </div>
        <div style={{overflowY:"auto",flex:1,padding:"20px",display:"flex",flexDirection:"column",gap:20}}>

          <div><div className="section-label">Basic Info</div>
            <div style={{display:"grid",gridTemplateColumns:"2fr 1fr",gap:10,marginBottom:10}}>
              <FInput label="Song Title *" value={form.title} onChange={e=>set("title",e.target.value)} placeholder="Untitled"/>
              <FInput label="Version"      value={form.version} onChange={e=>set("version",e.target.value)}/>
            </div>
            <div>
              <div className="meta-label" style={{marginBottom:5}}>Artist</div>
              <ArtistSearchDropdown
                artistId={form.artistId}
                artistName={form.artist}
                artists={artists}
                onUpdate={({ artistId, artist }) => { set("artistId", artistId); set("artist", artist); }}
                onNewArtist={onNewArtist}
                inputStyle={iStyle}
              />
            </div>
          </div>

          <div><div className="section-label">Metadata</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10,marginBottom:10}}>
              <FInput label="BPM" type="number" value={form.bpm} onChange={e=>set("bpm",e.target.value)}/>
              <FSelect label="Key" options={KEY_OPTIONS} value={form.key} onChange={e=>set("key",e.target.value)}/>
              <FInput label="Duration" value={form.duration} onChange={e=>set("duration",e.target.value)} placeholder="3:30"/>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10,marginBottom:10}}>
              <FInput label="ISRC" value={form.isrc} onChange={e=>set("isrc",e.target.value)} placeholder="AU-XXX-26-00000" mono/>
              <FInput label="ISWC" value={form.iswc} onChange={e=>set("iswc",e.target.value)} placeholder="T-000.000.000-0" mono/>
              <FInput label="PRO"  value={form.pro}  onChange={e=>set("pro",e.target.value)}/>
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
              <FSelect label="Genre"  options={GENRE_OPTIONS}  value={form.genre}  onChange={e=>set("genre",e.target.value)}/>
              <FSelect label="Status" options={STATUS_OPTIONS} value={form.status} onChange={e=>set("status",e.target.value)}/>
            </div>
          </div>

          <div><div className="section-label">Attributes</div>
            <div className="info-box" style={{display:"flex",flexDirection:"column",gap:10}}>
              <Toggle label="Sync Ready"       value={form.syncReady}       onChange={v=>set("syncReady",v)}/>
              <Toggle label="Stems Available"  value={form.stemsAvailable}  onChange={v=>set("stemsAvailable",v)}/>
              <Toggle label="Instrumental"     value={form.instrumental}    onChange={v=>set("instrumental",v)}/>
            </div>
          </div>

          <div><div className="section-label">Moods & Tags</div>
            <div style={{display:"flex",gap:5,flexWrap:"wrap"}}>
              {MOOD_OPTIONS.map(m=>(
                <button key={m} onClick={()=>toggleMood(m)} style={{padding:"3px 10px",borderRadius:5,fontSize:12,cursor:"pointer",background:form.moods.includes(m)?"var(--accent)":"var(--bg-2)",color:form.moods.includes(m)?"#fff":"var(--text-3)",border:"1px solid "+(form.moods.includes(m)?"var(--accent)":"var(--border)"),transition:"all 0.1s"}}>{m}</button>
              ))}
            </div>
          </div>

          <div><div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8}}>
            <div className="section-label" style={{margin:0}}>Writer Splits</div>
            <div style={{display:"flex",gap:8,alignItems:"center"}}>
              <span className="mono" style={{fontSize:12,fontWeight:700,color:splitsOk?"#059669":"#d97706"}}>{total}%</span>
              <button className="btn-ghost" onClick={addSplit} style={{fontSize:11}}>+ Add</button>
            </div>
          </div>
          <div style={{height:8,borderRadius:4,background:"var(--border)",overflow:"hidden",display:"flex",gap:1,marginBottom:10}}>
            {form.splits.map((s,i)=><div key={i} style={{width:`${s.writer}%`,height:"100%",background:SPLIT_COLORS[i%SPLIT_COLORS.length],transition:"width 0.15s"}}></div>)}
          </div>
          <div style={{display:"flex",flexDirection:"column",gap:6}}>
            {form.splits.map((s,i)=>(
              <div key={i} style={{display:"grid",gridTemplateColumns:"1fr 120px 72px 72px 20px",gap:6,alignItems:"center"}}>
                <CollabSearchDropdown
                  split={s}
                  collabs={collabs}
                  onUpdateSplit={updated => set("splits", form.splits.map((sp,j) => j===i ? updated : sp))}
                  onNewCollab={onNewCollab}
                  inputStyle={{...iStyle,fontSize:12}}
                />
                <input value={s.role} onChange={e=>updateSplit(i,"role",e.target.value)} placeholder="Role" style={{...iStyle,fontSize:12}}/>
                <div style={{display:"flex",alignItems:"center",gap:3}}>
                  <input type="number" min="0" max="100" value={s.writer} onChange={e=>updateSplit(i,"writer",e.target.value)} style={{...iStyle,fontFamily:"var(--mono)",textAlign:"right",fontSize:12}}/>
                  <span style={{fontSize:11,color:"var(--text-3)"}}>%</span>
                </div>
                <div style={{display:"flex",alignItems:"center",gap:3}}>
                  <input type="number" min="0" max="100" value={s.publisher} onChange={e=>updateSplit(i,"publisher",e.target.value)} style={{...iStyle,fontFamily:"var(--mono)",textAlign:"right",fontSize:12}}/>
                  <span style={{fontSize:11,color:"var(--text-3)"}}>%</span>
                </div>
                {form.splits.length>1?<button onClick={()=>removeSplit(i)} style={{background:"none",border:"none",color:"var(--text-3)",cursor:"pointer",fontSize:14,padding:0}}>✕</button>:<div></div>}
              </div>
            ))}
          </div>
          {!splitsOk && <div style={{fontSize:12,color:"#d97706",marginTop:4}}>⚠ {total<100?`${100-total}% unassigned`:`${total-100}% over-allocated`}</div>}
          </div>

          <div><div className="section-label">Rights</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 80px",gap:10}}>
              <FInput label="Master Owner"     value={form.masterOwner}     onChange={e=>set("masterOwner",e.target.value)}/>
              <FInput label="Publishing Owner" value={form.publishingOwner} onChange={e=>set("publishingOwner",e.target.value)}/>
              <FInput label="Own %" type="number" value={form.ownershipPct} onChange={e=>set("ownershipPct",e.target.value)}/>
            </div>
          </div>

          <div><div className="section-label">Notes</div>
            <textarea value={form.notes} onChange={e=>set("notes",e.target.value)} placeholder="Any additional notes…"
              style={{width:"100%",minHeight:70,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-2)",color:"var(--text)",fontSize:13,fontFamily:"var(--font)",resize:"vertical",outline:"none"}}
              onFocus={e=>e.target.style.borderColor="var(--accent)"} onBlur={e=>e.target.style.borderColor="var(--border)"}/>
          </div>
        </div>

        <div style={{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:8,padding:"12px 20px",borderTop:"1px solid var(--border)"}}>
          {!form.title && <span style={{fontSize:12,color:"#d97706",marginRight:"auto"}}>Song title required</span>}
          {form.title && !splitsOk && <span style={{fontSize:12,color:"#d97706",marginRight:"auto"}}>Fix splits before saving</span>}
          {form.title && splitsOk && <span style={{fontSize:12,color:"#059669",marginRight:"auto"}}>✓ Ready to create</span>}
          <button className="btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn-accent" onClick={handleSave} disabled={!form.title||!splitsOk} style={{opacity:(!form.title||!splitsOk)?0.4:1}}>Create Song</button>
        </div>
      </div>
    </>
  );
}

// ─── Notifications Panel ──────────────────────────────────────────────────────

function NotificationsPanel({ songs, briefs, publishers: publishersProp, onClose }) {
  const allPublishers = publishersProp || PUBLISHERS;
  const notes = useMemo(() => {
    const items = [];
    songs.filter(s=>s.splitConflict).forEach(s=>
      items.push({type:"warning",title:"Split agreement pending",body:`"${s.title}" — all writers must sign before registration.`}));
    songs.filter(s=>(s.status==="Released"||s.status==="Mastered")&&!s.isrc).forEach(s=>
      items.push({type:"error",title:"Missing ISRC",body:`"${s.title}" is ${s.status} but has no ISRC assigned.`}));
    songs.filter(s=>s.status==="Released"&&!s.iswc).forEach(s=>
      items.push({type:"info",title:"ISWC not registered",body:`"${s.title}" — register with ${s.pro} to obtain an ISWC.`}));
    RELEASES.forEach(r=>{
      const items2=Object.values(r.checklist); const done=items2.filter(Boolean).length;
      if(done<items2.length) items.push({type:"info",title:"Release checklist incomplete",body:`"${r.title}" — ${Math.round(done/items2.length*100)}% complete. Release date: ${r.date}.`});
    });
    allPublishers.filter(p=>!isPublisherComplete(p)).forEach(p=>
      items.push({type:"warning",title:"Publisher missing PRO",body:`"${p.name}" — PRO affiliation is not set. Open the publisher to complete it.`}));
    const now = new Date();
    (briefs||[]).filter(b=>!["Landed","Passed","Expired"].includes(b.status)).forEach(b=>{
      if (b.followUpDate && !b.followUpDone && new Date(b.followUpDate) < now) {
        items.push({type:"warning",title:"Follow-up overdue",body:`"${b.title}"${b.client?" · "+b.client:""} — follow-up was due ${b.followUpDate}.`});
      }
      if (b.deadline) {
        const days=Math.ceil((new Date(b.deadline)-now)/86400000);
        if(days>=0&&days<=7) items.push({type:"info",title:"Brief deadline this week",body:`${b.client||""} brief — "${b.title}" due in ${days===0?"today":days+" day"+(days>1?"s":"")}.`});
      }
    });
    return items;
  }, [songs, briefs, allPublishers]);

  const TS = { warning:{icon:"⚠",c:"#d97706",bg:"#fef3c7"}, error:{icon:"⚑",c:"#dc2626",bg:"#fee2e2"}, info:{icon:"ℹ",c:"#2563eb",bg:"#dbeafe"} };
  const critical = notes.filter(n=>n.type==="error").length;
  const warnings = notes.filter(n=>n.type==="warning").length;

  return (
    <>
      <div style={{position:"fixed",inset:0,zIndex:299}} onClick={onClose}></div>
      <div style={{position:"fixed",top:56,right:14,width:340,background:"var(--card)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.12)",zIndex:300,overflow:"hidden",animation:"pageFade 0.12s ease"}}>
        <div style={{padding:"12px 16px",borderBottom:"1px solid var(--border)",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
          <span style={{fontWeight:600,fontSize:14}}>Notifications</span>
          <div style={{display:"flex",gap:8,alignItems:"center"}}>
            {critical>0&&<span style={{fontSize:10,background:"#dc2626",color:"#fff",padding:"1px 7px",borderRadius:10}}>{critical} critical</span>}
            {warnings>0&&<span style={{fontSize:10,background:"#d97706",color:"#fff",padding:"1px 7px",borderRadius:10}}>{warnings} warnings</span>}
          </div>
        </div>
        <div style={{maxHeight:420,overflowY:"auto"}}>
          {notes.length===0?(
            <div style={{padding:28,textAlign:"center",color:"var(--text-3)",fontSize:13}}>✓ All clear — no issues found.</div>
          ):notes.map((n,i)=>{
            const ts=TS[n.type];
            return(
              <div key={i} style={{padding:"12px 16px",borderBottom:"1px solid var(--border-sub)",display:"flex",gap:10}}>
                <div style={{width:24,height:24,borderRadius:6,background:ts.bg,color:ts.c,display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,flexShrink:0,marginTop:1}}>{ts.icon}</div>
                <div><div style={{fontWeight:500,fontSize:13}}>{n.title}</div><div style={{fontSize:12,color:"var(--text-3)",marginTop:2,lineHeight:1.5}}>{n.body}</div></div>
              </div>
            );
          })}
        </div>
        <div style={{padding:"8px 16px",borderTop:"1px solid var(--border)",fontSize:11,color:"var(--text-3)",textAlign:"center"}}>
          {notes.length} total · {critical} critical · {warnings} warnings
        </div>
      </div>
    </>
  );
}

// ─── Artist Drawer ────────────────────────────────────────────────────────────

function ArtistDrawer({ artist, songs, onClose, onSelectSong, onUpdateSong, onDelete, isCentered, onToggleCenter }) {
  if (!artist) return null;
  const artistSongs = songs.filter(s => s.artist === artist.name);
  const released   = artistSongs.filter(s => s.status === "Released").length;
  const syncReady  = artistSongs.filter(s => s.syncReady).length;
  const inProgress = artistSongs.filter(s => ["In Progress","Mixing","Demo"].includes(s.status)).length;
  const genres     = [...new Set(artistSongs.map(s => s.genre.split("/")[0].trim()))];

  const [confirmDel,  setConfirmDel]  = useState(false);
  const [blockMsg,    setBlockMsg]    = useState("");
  const [songSearch,  setSongSearch]  = useState("");
  const [showAddSong, setShowAddSong] = useState(false);

  const statusGroups = [
    {label:"Released",    color:"#059669"}, {label:"Mastered",    color:"#2563eb"},
    {label:"In Progress", color:"#d97706"}, {label:"Mixing",      color:"#d97706"},
    {label:"Demo",        color:"#9ca3af"},
  ].map(g => ({...g, count:artistSongs.filter(s=>s.status===g.label).length})).filter(g=>g.count>0);

  const assignSong = (song) => {
    if (!onUpdateSong) return;
    onUpdateSong(song.id, { artist: artist.name });
    setSongSearch(""); setShowAddSong(false);
  };

  const unassignSong = (song) => {
    if (!onUpdateSong) return;
    onUpdateSong(song.id, { artist: "" });
  };

  const availableSongs = songs.filter(s =>
    s.artist !== artist.name &&
    s.title.toLowerCase().includes(songSearch.toLowerCase())
  ).slice(0, 8);

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>
        <div className="drawer-header">
          <div style={{ display:"flex", alignItems:"center", gap:12 }}>
            <div style={{ width:44, height:44, borderRadius:12, background:`hsl(${artist.artworkHue},45%,90%)`, color:`hsl(${artist.artworkHue},45%,32%)`, display:"flex", alignItems:"center", justifyContent:"center", fontWeight:700, fontSize:15, flexShrink:0 }}>
              {artist.name.split(" ").map(n=>n[0]).join("").slice(0,2)}
            </div>
            <div>
              <div className="drawer-title">{artist.name}</div>
              <div style={{ fontSize:12, color:"var(--text-3)", marginTop:2 }}>{artist.genre}</div>
            </div>
          </div>
          <div style={{ display:"flex", gap:6, alignItems:"center" }}>
            {!confirmDel && !blockMsg && (
              <button onClick={() => {
                if (artistSongs.length > 0) { setBlockMsg(`Can't delete — ${artistSongs.length} song${artistSongs.length!==1?"s":""} assigned to this artist. Reassign them first.`); return; }
                setConfirmDel(true);
              }} style={{ fontSize:11.5, padding:"4px 10px", borderRadius:6, border:"1px solid #fca5a5", background:"#fff1f2", color:"#dc2626", cursor:"pointer", fontFamily:"var(--font)" }}>Delete</button>
            )}
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        {blockMsg && (
          <div style={{ margin:"12px 20px", padding:"12px 14px", background:"#fef3c7", border:"1px solid #fcd34d", borderRadius:8, display:"flex", justifyContent:"space-between", alignItems:"center", gap:12 }}>
            <div style={{ fontSize:13, color:"#92400e" }}>{blockMsg}</div>
            <button onClick={()=>setBlockMsg("")} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)", flexShrink:0 }}>Dismiss</button>
          </div>
        )}
        {confirmDel && (
          <div style={{ margin:"12px 20px", padding:"12px 14px", background:"#fff1f2", border:"1px solid #fca5a5", borderRadius:8, display:"flex", justifyContent:"space-between", alignItems:"center", gap:12 }}>
            <div style={{ fontSize:13, color:"#7f1d1d" }}>Delete <strong>{artist.name}</strong>? This can't be undone.</div>
            <div style={{ display:"flex", gap:8, flexShrink:0 }}>
              <button onClick={()=>setConfirmDel(false)} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>Cancel</button>
              <button onClick={()=>onDelete(artist.id)} style={{ fontSize:12, padding:"4px 10px", borderRadius:6, border:"none", background:"#dc2626", color:"#fff", cursor:"pointer", fontFamily:"var(--font)" }}>Delete</button>
            </div>
          </div>
        )}

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1, display:"flex", flexDirection:"column", gap:20 }}>

          {/* Status badge */}
          <div style={{ display:"flex", gap:6 }}>
            <Badge color={artist.active?"#166534":"#6b7280"} bg={artist.active?"#dcfce7":"#f3f4f6"}>
              {artist.active ? "Active" : "Inactive"}
            </Badge>
            {genres.slice(0,3).map(g => <Badge key={g}>{g}</Badge>)}
          </div>

          {/* Stats */}
          <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:8 }}>
            {[
              { label:"Total Songs",  value:artistSongs.length, color:"var(--accent)" },
              { label:"Released",     value:released,           color:"#059669" },
              { label:"Sync Ready",   value:syncReady,          color:"#2563eb" },
            ].map(s => (
              <div key={s.label} className="info-box" style={{ textAlign:"center", padding:"12px 8px" }}>
                <div style={{ fontSize:26, fontWeight:700, color:s.color, letterSpacing:"-0.02em" }}>{s.value}</div>
                <div style={{ fontSize:10.5, color:"var(--text-3)", marginTop:3 }}>{s.label}</div>
              </div>
            ))}
          </div>

          {/* Description */}
          {artist.description && (
            <div>
              <div className="section-label">About</div>
              <div className="info-box" style={{ fontSize:13, lineHeight:1.65, color:"var(--text-2)" }}>{artist.description}</div>
            </div>
          )}

          {/* Status breakdown */}
          {statusGroups.length > 0 && (
            <div>
              <div className="section-label">Catalog Status</div>
              <div className="info-box" style={{ display:"flex", flexDirection:"column", gap:10 }}>
                {statusGroups.map(g => (
                  <div key={g.label}>
                    <div style={{ display:"flex", justifyContent:"space-between", fontSize:12, marginBottom:4 }}>
                      <span style={{ color:"var(--text-2)" }}>{g.label}</span>
                      <span className="mono" style={{ fontWeight:600 }}>{g.count}</span>
                    </div>
                    <div style={{ height:5, borderRadius:3, background:"var(--border)", overflow:"hidden" }}>
                      <div style={{ width:`${(g.count/artistSongs.length)*100}%`, height:"100%", background:g.color, borderRadius:3 }}></div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Song list */}
          <div>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:7 }}>
              <div className="section-label" style={{ margin:0 }}>Catalog ({artistSongs.length} song{artistSongs.length!==1?"s":""})</div>
              {onUpdateSong && (
                <button onClick={() => { setShowAddSong(s => !s); setSongSearch(""); }}
                  style={{ fontSize:11, padding:"2px 9px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", cursor:"pointer", fontFamily:"var(--font)" }}>
                  {showAddSong ? "Cancel" : "+ Add Song"}
                </button>
              )}
            </div>

            {showAddSong && (
              <div style={{ marginBottom:10, position:"relative" }}>
                <input
                  value={songSearch}
                  onChange={e => setSongSearch(e.target.value)}
                  placeholder="Search songs…"
                  autoFocus
                  style={{ width:"100%", padding:"6px 10px", borderRadius:6, border:"1px solid var(--accent)", background:"var(--bg)", color:"var(--text)", fontSize:12.5, fontFamily:"var(--font)", outline:"none", boxSizing:"border-box" }}
                />
                {availableSongs.length > 0 && (
                  <div style={{ position:"absolute", top:"100%", left:0, right:0, background:"var(--card)", border:"1px solid var(--border)", borderRadius:8, boxShadow:"var(--shadow)", zIndex:10, overflow:"hidden", marginTop:2 }}>
                    {availableSongs.map(s => (
                      <div key={s.id} onClick={() => assignSong(s)}
                        style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"8px 12px", cursor:"pointer", fontSize:13, borderBottom:"1px solid var(--border-sub)" }}
                        onMouseEnter={e => e.currentTarget.style.background="var(--bg-2)"}
                        onMouseLeave={e => e.currentTarget.style.background=""}
                      >
                        <span style={{ fontWeight:500 }}>{s.title}</span>
                        <span style={{ fontSize:11, color:"var(--text-3)" }}>{s.genre} · {s.status}</span>
                      </div>
                    ))}
                  </div>
                )}
                {availableSongs.length === 0 && songSearch && (
                  <div style={{ padding:"8px 10px", fontSize:12, color:"var(--text-3)" }}>No songs found</div>
                )}
              </div>
            )}

            {artistSongs.length === 0 && !showAddSong ? (
              <div style={{ fontSize:13, color:"var(--text-3)", padding:"10px 0" }}>No songs assigned to this artist yet.</div>
            ) : (
              <div style={{ display:"flex", flexDirection:"column", gap:6 }}>
                {artistSongs.map(s => (
                  <div key={s.id} className="info-box"
                    style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"10px 12px", transition:"border-color 0.12s" }}
                    onMouseEnter={e => e.currentTarget.style.borderColor="var(--accent)"}
                    onMouseLeave={e => e.currentTarget.style.borderColor="var(--border)"}
                  >
                    <div onClick={() => onSelectSong && onSelectSong(s)} style={{ flex:1, cursor:onSelectSong?"pointer":"default" }}>
                      <div style={{ fontWeight:500, fontSize:13 }}>{s.title}</div>
                      <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{s.genre} · {s.version}</div>
                    </div>
                    <div style={{ display:"flex", gap:5, alignItems:"center", flexShrink:0 }}>
                      {s.syncReady && <Badge color="#166534" bg="#dcfce7">Sync</Badge>}
                      <StatusBadge status={s.status} />
                      {onUpdateSong && (
                        <button onClick={() => unassignSong(s)} title="Remove from artist"
                          style={{ width:22, height:22, borderRadius:5, border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-3)", fontSize:11, cursor:"pointer", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>✕</button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div style={{ height:8 }}></div>
        </div>
      </div>
    </>
  );
}

// ─── Contact Drawer ───────────────────────────────────────────────────────────

const CONTACT_TYPE_COLORS = { "Agency":"#7c6fff", "Sub-Publisher":"#22c55e", "Supervisor":"#f59e0b", "Label":"#f472b6" };

function ContactDrawer({ contact, songs, onClose, isCentered, onToggleCenter }) {
  if (!contact) return null;
  const linkedSongs = (songs||[]).filter(s => (s.agencyIds||[]).includes(contact.id));
  const typeColor = CONTACT_TYPE_COLORS[contact.type] || "var(--text-3)";
  const initials = contact.name.split(" ").map(w=>w[0]).join("").slice(0,2).toUpperCase();

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>
        <div className="drawer-header">
          <div style={{ display:"flex", alignItems:"center", gap:12 }}>
            <div style={{ width:44, height:44, borderRadius:12, background: typeColor+"22", color:typeColor, display:"flex", alignItems:"center", justifyContent:"center", fontWeight:700, fontSize:15, flexShrink:0 }}>{initials}</div>
            <div>
              <div className="drawer-title" style={{ fontSize:17 }}>{contact.name}</div>
              <div style={{ fontSize:11, marginTop:2 }}>
                <span style={{ background: typeColor+"22", color:typeColor, borderRadius:4, padding:"1px 7px", fontWeight:500 }}>{contact.type}</span>
              </div>
            </div>
          </div>
          <div style={{ display:"flex", gap:6, alignItems:"center" }}>
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1 }}>
          <div style={{ display:"flex", flexDirection:"column", gap:10, marginBottom:16 }}>
            {contact.email && (
              <div>
                <div className="meta-label">Email</div>
                <a href={"mailto:"+contact.email} style={{ fontSize:13, color:"var(--accent)", textDecoration:"none" }}>{contact.email}</a>
              </div>
            )}
            {contact.website && (
              <div>
                <div className="meta-label">Website</div>
                <a href={"https://"+contact.website.replace(/^https?:\/\//,"")} target="_blank" rel="noopener noreferrer" style={{ fontSize:13, color:"var(--accent)", textDecoration:"none" }}>{contact.website}</a>
              </div>
            )}
            {contact.notes && (
              <div>
                <div className="meta-label">Notes</div>
                <div className="info-box" style={{ fontSize:13, lineHeight:1.65, color:"var(--text-2)" }}>{contact.notes}</div>
              </div>
            )}
          </div>

          <div className="section-label">Linked Songs ({linkedSongs.length})</div>
          {linkedSongs.length === 0 ? (
            <div style={{ fontSize:13, color:"var(--text-3)", padding:"12px 0" }}>No songs linked yet. Edit a song and add this contact via its agency list.</div>
          ) : (
            <div style={{ display:"flex", flexDirection:"column", gap:1, border:"1px solid var(--border)", borderRadius:8, overflow:"hidden" }}>
              {linkedSongs.map(s => (
                <div key={s.id} style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"9px 13px", borderBottom:"1px solid var(--border-sub)", background:"var(--card)" }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:500 }}>{s.title}</div>
                    <div style={{ fontSize:11, color:"var(--text-3)" }}>{s.version} · {s.genre}</div>
                  </div>
                  <div style={{ display:"flex", gap:5, alignItems:"center" }}>
                    {s.syncReady && <Badge color="#166534" bg="#dcfce7">Sync Ready</Badge>}
                    <StatusBadge status={s.status} />
                  </div>
                </div>
              ))}
            </div>
          )}
          <div style={{ height:16 }}></div>
        </div>
      </div>
    </>
  );
}

// ─── New Brief Modal ──────────────────────────────────────────────────────────

function NewBriefModal({ onClose, onSave }) {
  const [form, setForm] = useState({ title:"", client:"", deadline:"", status:"Active" });
  const set = (k,v) => setForm(f => ({...f,[k]:v}));
  const iStyle = { width:"100%", padding:"7px 10px", border:"1px solid var(--border)", borderRadius:6, background:"var(--bg-2)", color:"var(--text)", fontSize:13, fontFamily:"var(--font)", outline:"none" };
  const lbl   = { fontSize:9.5, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.07em", fontWeight:500, marginBottom:4, display:"block" };

  useEffect(() => { document.getElementById("new-brief-title")?.focus(); }, []);

  return (
    <>
      <div style={{ position:"fixed", inset:0, background:"rgba(0,0,0,0.28)", zIndex:400, backdropFilter:"blur(2px)" }} onClick={onClose}></div>
      <div style={{ position:"fixed", top:"26%", left:"50%", transform:"translateX(-50%)", width:400, background:"var(--card)", border:"1px solid var(--border)", borderRadius:12, boxShadow:"0 20px 60px rgba(0,0,0,0.14)", zIndex:401, overflow:"hidden", animation:"pageFade 0.15s ease" }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"14px 18px", borderBottom:"1px solid var(--border)" }}>
          <div style={{ fontWeight:700, fontSize:15 }}>New Sync Brief</div>
          <button className="icon-btn" onClick={onClose}>✕</button>
        </div>
        <div style={{ padding:"18px", display:"flex", flexDirection:"column", gap:12 }}>
          <div>
            <label style={lbl}>Brief Title *</label>
            <input id="new-brief-title" style={iStyle} value={form.title} onChange={e=>set("title",e.target.value)} placeholder="Nike Action Sports Campaign…" />
          </div>
          <div>
            <label style={lbl}>Client / Brand</label>
            <input style={iStyle} value={form.client} onChange={e=>set("client",e.target.value)} placeholder="Nike, Netflix, Calm…" />
          </div>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 }}>
            <div>
              <label style={lbl}>Deadline</label>
              <input style={iStyle} type="date" value={form.deadline} onChange={e=>set("deadline",e.target.value)} />
            </div>
            <div>
              <label style={lbl}>Status</label>
              <select style={iStyle} value={form.status} onChange={e=>set("status",e.target.value)}>
                <option>Active</option><option>Submitted</option><option>In Review</option><option>Shortlisted</option>
              </select>
            </div>
          </div>
        </div>
        <div style={{ display:"flex", justifyContent:"flex-end", gap:8, padding:"12px 18px", borderTop:"1px solid var(--border)" }}>
          {!form.title.trim() && <span style={{ fontSize:12, color:"var(--text-3)", marginRight:"auto", alignSelf:"center" }}>Title required</span>}
          <button className="btn-ghost" onClick={onClose}>Cancel</button>
          <button className="btn-accent" onClick={() => { if(form.title.trim()) onSave({...form, mood:[], genre:[], submittedSongs:[], source:"manual"}); }}
            disabled={!form.title.trim()} style={{ opacity:!form.title.trim()?0.4:1 }}>
            Create & Edit →
          </button>
        </div>
      </div>
    </>
  );
}

// ─── Brief Drawer ─────────────────────────────────────────────────────────────

const BRIEF_STATUSES  = ["Active","Submitted","In Review","Shortlisted","Landed","Passed","Expired"];
const BRIEF_PLACEMENTS = ["TVC","Streaming Series","Film","Trailer","In-App","Social Media","Game","Radio","Other"];
const BRIEF_TERRITORIES = ["Worldwide","North America","Europe","Asia-Pacific","Australia/NZ","UK","Custom"];
const BRIEF_FORMATS = ["Any","Stereo Only","Stereo + Stems","Instrumental Required","All Versions"];

function BriefDrawer({ brief, songs, contacts, onClose, onUpdate, onDelete, isCentered, onToggleCenter }) {
  if (!brief) return null;
  const [editMode,       setEditMode]       = useState(false);
  const [draft,          setDraft]          = useState(null);
  const [songSearch,     setSongSearch]     = useState("");
  const [confirmDelete,  setConfirmDelete]  = useState(false);

  useEffect(() => {
    setEditMode(false); setConfirmDelete(false); setDraft(null); setSongSearch("");
  }, [brief.id]);

  const set = (k,v) => setDraft(d => ({...d,[k]:v}));

  const openEdit = () => {
    setDraft({ ...brief, mood: brief.mood||[], genre: brief.genre||[], submittedSongs: brief.submittedSongs||[] });
    setEditMode(true);
  };

  const handleSave = () => { if (draft) { onUpdate(brief.id, draft); setEditMode(false); } };

  const now = new Date();
  const isOverdue = brief.followUpDate && !brief.followUpDone && new Date(brief.followUpDate) < now;
  const isArchived = ["Landed","Passed","Expired"].includes(brief.status);

  const submittedSongs = (editMode ? draft?.submittedSongs : brief.submittedSongs) || [];

  const addSong = (song) => {
    if (submittedSongs.some(ss => String(ss.songId) === String(song.id))) return;
    const entry = { songId: String(song.id), title: song.title, submittedAt: new Date().toISOString().split("T")[0], notes:"" };
    const updated = [...submittedSongs, entry];
    if (editMode) set("submittedSongs", updated); else onUpdate(brief.id, { submittedSongs: updated });
    setSongSearch("");
  };

  const removeSong = (songId) => {
    const updated = submittedSongs.filter(ss => String(ss.songId) !== String(songId));
    if (editMode) set("submittedSongs", updated); else onUpdate(brief.id, { submittedSongs: updated });
  };

  const updateSongNotes = (songId, notes) => {
    const updated = submittedSongs.map(ss => String(ss.songId) === String(songId) ? {...ss,notes} : ss);
    if (editMode) set("submittedSongs", updated); else onUpdate(brief.id, { submittedSongs: updated });
  };

  const searchResults = useMemo(() => {
    const q = songSearch.trim().toLowerCase();
    const already = new Set(submittedSongs.map(ss => String(ss.songId)));
    const pool = songs.filter(s => !already.has(String(s.id)));
    if (!q) return pool.filter(s => s.syncReady).slice(0, 6);
    return pool.filter(s => s.title.toLowerCase().includes(q) || (s.genre||"").toLowerCase().includes(q)).slice(0, 6);
  }, [songSearch, songs, submittedSongs]);

  const inp  = { width:"100%", padding:"6px 9px", borderRadius:6, border:"1px solid var(--border)", background:"var(--bg)", color:"var(--text)", fontSize:13, fontFamily:"var(--font)", outline:"none" };
  const lbl  = { fontSize:9.5, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.07em", fontWeight:500, marginBottom:4, display:"block" };
  const b    = editMode ? (draft||brief) : brief;

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>
        {/* Header */}
        <div className="drawer-header">
          <div style={{ flex:1, minWidth:0 }}>
            <div className="drawer-title" style={{ overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{brief.title||"Untitled Brief"}</div>
            <div style={{ fontSize:12, color:"var(--text-3)", marginTop:2 }}>{brief.client||"—"}{brief.placement?" · "+brief.placement:""}</div>
          </div>
          <div style={{ display:"flex", gap:6, flexShrink:0 }}>
            {!editMode ? (
              <>
                {confirmDelete
                  ? <><button className="btn-ghost" style={{fontSize:11,color:"var(--text-3)"}} onClick={()=>setConfirmDelete(false)}>Cancel</button>
                       <button className="btn-ghost" style={{fontSize:11,color:"#e05c5c",borderColor:"#e05c5c"}} onClick={()=>{onDelete(brief.id);onClose();}}>Confirm</button></>
                  : <button className="btn-ghost" style={{fontSize:11,color:"#e05c5c"}} onClick={()=>setConfirmDelete(true)}>Delete</button>}
                <button className="btn-ghost" style={{fontSize:11}} onClick={openEdit}>Edit</button>
              </>
            ) : (
              <>
                <button className="btn-ghost" style={{fontSize:11,color:"var(--text-3)"}} onClick={()=>setEditMode(false)}>Cancel</button>
                <button className="btn-ghost" style={{fontSize:11,color:"var(--accent)",borderColor:"var(--accent)"}} onClick={handleSave}>Save</button>
              </>
            )}
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1 }}>

          {/* Status row */}
          <div style={{ display:"flex", gap:8, alignItems:"center", marginBottom:14, flexWrap:"wrap" }}>
            {editMode
              ? <select style={{...inp,width:"auto"}} value={b.status||"Active"} onChange={e=>set("status",e.target.value)}>
                  {BRIEF_STATUSES.map(s=><option key={s}>{s}</option>)}
                </select>
              : <StatusBadge status={brief.status} />}
            {isOverdue && !editMode && <span className="followup-badge">Follow-up overdue</span>}
            {brief.deadline && !editMode && (
              <span style={{fontSize:12,color:"var(--text-3)",marginLeft:"auto"}}>
                Due {new Date(brief.deadline).toLocaleDateString("en-AU",{day:"numeric",month:"long",year:"numeric"})}
              </span>
            )}
          </div>

          {/* VIEW — info grid */}
          {!editMode && (
            <>
              <div className="meta-grid" style={{marginBottom:12}}>
                {[
                  ["Client",      brief.client||"—"],
                  ["Placement",   brief.placement||"—"],
                  ["Territory",   brief.territory||"—"],
                  ["Exclusivity", brief.exclusivity||"—"],
                  ["Budget",      brief.budget||"—"],
                  ["Est. Value",  brief.budgetEstimate ? "$"+Number(brief.budgetEstimate).toLocaleString() : "—"],
                  ["Format",      brief.formatRequired||"—"],
                  ["Duration",    brief.duration||"—"],
                ].map(([label,val]) => (
                  <div key={label} className="meta-cell">
                    <div className="meta-label">{label}</div>
                    <div className="meta-value" style={{fontSize:12.5}}>{val}</div>
                  </div>
                ))}
              </div>
              {((brief.mood||[]).length>0||(brief.genre||[]).length>0||brief.bpmRange) && (
                <div style={{display:"flex",gap:4,flexWrap:"wrap",marginBottom:12}}>
                  {(brief.mood||[]).map(m=><Badge key={m} color="#5b21b6" bg="#ede9fe">{m}</Badge>)}
                  {(brief.genre||[]).map(g=><Badge key={g}>{g}</Badge>)}
                  {brief.bpmRange&&<Badge>{brief.bpmRange} bpm</Badge>}
                </div>
              )}
              {brief.description && (
                <>
                  <div className="section-label">Brief Description</div>
                  <div className="info-box" style={{fontSize:13,lineHeight:1.65,color:"var(--text-2)",marginBottom:12,whiteSpace:"pre-wrap"}}>{brief.description}</div>
                </>
              )}
              {brief.submissionInstructions && (
                <>
                  <div className="section-label">Submission Instructions</div>
                  <div className="info-box" style={{fontSize:13,lineHeight:1.6,color:"var(--text-2)",marginBottom:12}}>
                    {brief.submissionInstructions}
                    {brief.submissionLink && <a href={brief.submissionLink} target="_blank" rel="noopener noreferrer" style={{display:"block",marginTop:6,color:"var(--accent)",fontSize:12,textDecoration:"none"}}>↗ Submission portal</a>}
                  </div>
                </>
              )}
            </>
          )}

          {/* EDIT — full form */}
          {editMode && draft && (
            <div style={{display:"flex",flexDirection:"column",gap:12,marginBottom:16}}>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                <div style={{gridColumn:"1/-1"}}>
                  <label style={lbl}>Brief Title</label>
                  <input style={inp} value={draft.title||""} onChange={e=>set("title",e.target.value)} placeholder="Brief name" />
                </div>
                <div>
                  <label style={lbl}>Client / Brand</label>
                  <input style={inp} value={draft.client||""} onChange={e=>set("client",e.target.value)} placeholder="Nike, Netflix…" />
                </div>
                <div>
                  <label style={lbl}>Source Contact</label>
                  <select style={inp} value={draft.sourceContactId||""} onChange={e=>set("sourceContactId",e.target.value)}>
                    <option value="">— None —</option>
                    {(contacts||[]).map(c=><option key={c.id} value={c.id}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label style={lbl}>Placement Type</label>
                  <select style={inp} value={draft.placement||""} onChange={e=>set("placement",e.target.value)}>
                    <option value="">— Select —</option>
                    {BRIEF_PLACEMENTS.map(p=><option key={p}>{p}</option>)}
                  </select>
                </div>
                <div>
                  <label style={lbl}>Territory</label>
                  <select style={inp} value={draft.territory||""} onChange={e=>set("territory",e.target.value)}>
                    <option value="">— Select —</option>
                    {BRIEF_TERRITORIES.map(t=><option key={t}>{t}</option>)}
                  </select>
                </div>
                <div>
                  <label style={lbl}>Exclusivity</label>
                  <select style={inp} value={draft.exclusivity||""} onChange={e=>set("exclusivity",e.target.value)}>
                    <option value="">— Select —</option>
                    <option>Exclusive</option><option>Non-Exclusive</option><option>TBD</option>
                  </select>
                </div>
                <div>
                  <label style={lbl}>Submission Deadline</label>
                  <input style={inp} type="date" value={draft.deadline||""} onChange={e=>set("deadline",e.target.value)} />
                </div>
                <div>
                  <label style={lbl}>Budget (text)</label>
                  <input style={inp} value={draft.budget||""} onChange={e=>set("budget",e.target.value)} placeholder="$15,000 / MFN / TBD" />
                </div>
                <div>
                  <label style={lbl}>Est. Value ($)</label>
                  <input style={inp} type="number" value={draft.budgetEstimate||""} onChange={e=>set("budgetEstimate",e.target.value?Number(e.target.value):null)} placeholder="Pipeline tracking" />
                </div>
                <div>
                  <label style={lbl}>Format Required</label>
                  <select style={inp} value={draft.formatRequired||""} onChange={e=>set("formatRequired",e.target.value)}>
                    <option value="">— Any —</option>
                    {BRIEF_FORMATS.map(f=><option key={f}>{f}</option>)}
                  </select>
                </div>
                <div>
                  <label style={lbl}>Duration</label>
                  <input style={inp} value={draft.duration||""} onChange={e=>set("duration",e.target.value)} placeholder="60–90 seconds" />
                </div>
                <div>
                  <label style={lbl}>BPM Range</label>
                  <input style={inp} value={draft.bpmRange||""} onChange={e=>set("bpmRange",e.target.value)} placeholder="80–130" />
                </div>
                <div style={{gridColumn:"1/-1"}}>
                  <label style={lbl}>Mood (comma-separated)</label>
                  <input style={inp} value={(draft.mood||[]).join(", ")} onChange={e=>set("mood",e.target.value.split(",").map(m=>m.trim()).filter(Boolean))} placeholder="Cinematic, Dark, Emotional…" />
                </div>
                <div style={{gridColumn:"1/-1"}}>
                  <label style={lbl}>Genre (comma-separated)</label>
                  <input style={inp} value={(draft.genre||[]).join(", ")} onChange={e=>set("genre",e.target.value.split(",").map(g=>g.trim()).filter(Boolean))} placeholder="Electronic, Indie, Pop…" />
                </div>
                <div style={{gridColumn:"1/-1"}}>
                  <label style={lbl}>Brief Description</label>
                  <textarea style={{...inp,minHeight:80,resize:"vertical",lineHeight:1.6}} value={draft.description||""} onChange={e=>set("description",e.target.value)} placeholder="Paste or summarise the brief…" />
                </div>
                <div style={{gridColumn:"1/-1"}}>
                  <label style={lbl}>Submission Instructions</label>
                  <textarea style={{...inp,minHeight:60,resize:"vertical",lineHeight:1.6}} value={draft.submissionInstructions||""} onChange={e=>set("submissionInstructions",e.target.value)} placeholder="How to submit, file format, delivery…" />
                </div>
                <div style={{gridColumn:"1/-1"}}>
                  <label style={lbl}>Submission Portal URL</label>
                  <input style={{...inp,fontFamily:"var(--mono)",fontSize:12}} value={draft.submissionLink||""} onChange={e=>set("submissionLink",e.target.value)} placeholder="https://…" />
                </div>
              </div>
              {["Landed","Passed","Expired"].includes(draft.status) && (
                <div style={{background:"var(--bg-2)",border:"1px solid var(--border)",borderRadius:"var(--r)",padding:"12px 14px"}}>
                  <div className="section-label" style={{marginTop:0}}>Outcome</div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                    <div>
                      <label style={lbl}>Confirmed Fee ($)</label>
                      <input style={inp} type="number" value={draft.confirmedFee||""} onChange={e=>set("confirmedFee",e.target.value?Number(e.target.value):null)} placeholder="0" />
                    </div>
                    <div style={{gridColumn:"1/-1"}}>
                      <label style={lbl}>Outcome Notes</label>
                      <textarea style={{...inp,minHeight:56,resize:"vertical"}} value={draft.outcomeNotes||""} onChange={e=>set("outcomeNotes",e.target.value)} placeholder="Feedback from supervisor, what happened…" />
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Songs submitted */}
          <div className="section-label">Songs Submitted ({submittedSongs.length})</div>
          <div style={{position:"relative",marginBottom:songSearch||searchResults.length>0?0:10}}>
            <input
              style={{...inp,paddingLeft:28,marginBottom:0}}
              value={songSearch}
              onChange={e=>setSongSearch(e.target.value)}
              placeholder={songSearch?"Search songs…":"Browse sync-ready or search all songs…"}
            />
            <span style={{position:"absolute",left:9,top:"50%",transform:"translateY(-50%)",fontSize:13,color:"var(--text-3)",pointerEvents:"none"}}>⌕</span>
          </div>
          {searchResults.length>0 && (
            <div style={{border:"1px solid var(--border)",borderTop:"none",borderRadius:"0 0 var(--r) var(--r)",overflow:"hidden",maxHeight:196,overflowY:"auto",marginBottom:10}}>
              {!songSearch && <div style={{padding:"4px 10px",fontSize:9.5,color:"var(--text-3)",background:"var(--bg-2)",letterSpacing:"0.06em",textTransform:"uppercase",borderBottom:"1px solid var(--border-sub)"}}>Sync ready</div>}
              {searchResults.map(s=>(
                <div key={s.id} onClick={()=>addSong(s)}
                  style={{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 12px",cursor:"pointer",borderBottom:"1px solid var(--border-sub)",background:"var(--card)",transition:"background 0.08s"}}
                  onMouseEnter={e=>e.currentTarget.style.background="var(--bg-2)"}
                  onMouseLeave={e=>e.currentTarget.style.background="var(--card)"}
                >
                  <div>
                    <div style={{fontSize:13,fontWeight:500}}>{s.title}</div>
                    <div style={{fontSize:11,color:"var(--text-3)"}}>{s.genre} · {s.bpm} BPM · {s.key}</div>
                  </div>
                  <div style={{display:"flex",gap:4,alignItems:"center"}}>
                    {s.syncReady&&<Badge color="#166534" bg="#dcfce7" style={{fontSize:9}}>Sync</Badge>}
                    {s.stemsAvailable&&<Badge color="var(--accent)" bg="var(--accent-dim)" style={{fontSize:9}}>Stems</Badge>}
                    <span style={{fontSize:11,color:"var(--accent)",marginLeft:4}}>+ Add</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          {submittedSongs.length>0 ? (
            <div style={{display:"flex",flexDirection:"column",gap:6,marginBottom:16,marginTop:10}}>
              {submittedSongs.map(ss=>(
                <div key={ss.songId} style={{background:"var(--bg-2)",border:"1px solid var(--border)",borderRadius:"var(--r)",padding:"10px 12px"}}>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}}>
                    <div>
                      <div style={{fontSize:13,fontWeight:500}}>{ss.title||"Unknown Song"}</div>
                      <div style={{fontSize:11,color:"var(--text-3)",marginTop:1}}>Submitted {ss.submittedAt||"—"}</div>
                    </div>
                    <button onClick={()=>removeSong(ss.songId)} style={{background:"none",border:"none",color:"var(--text-3)",cursor:"pointer",fontSize:14,padding:"0 2px"}}>✕</button>
                  </div>
                  <input style={{...inp,fontSize:12,padding:"4px 8px"}} value={ss.notes||""} onChange={e=>updateSongNotes(ss.songId,e.target.value)} placeholder="Notes: format sent, version, details…" />
                </div>
              ))}
            </div>
          ) : (
            <div style={{fontSize:12,color:"var(--text-3)",padding:"8px 0 14px"}}>No songs submitted yet — search above to add.</div>
          )}

          {/* Follow-up */}
          <div className="section-label">Follow-up Reminder</div>
          <div style={{display:"flex",gap:8,alignItems:"center",marginBottom:16,flexWrap:"wrap"}}>
            <input style={{...inp,width:160}} type="date" value={brief.followUpDate||""} onChange={e=>onUpdate(brief.id,{followUpDate:e.target.value,followUpDone:false})} />
            {brief.followUpDate && (
              <button onClick={()=>onUpdate(brief.id,{followUpDone:!brief.followUpDone})}
                style={{padding:"6px 12px",borderRadius:"var(--r)",border:"1px solid var(--border)",background:brief.followUpDone?"#dcfce7":"var(--bg-2)",color:brief.followUpDone?"#166534":"var(--text-2)",fontSize:12,cursor:"pointer",fontFamily:"var(--font)",transition:"all 0.12s"}}>
                {brief.followUpDone?"✓ Done":"Mark done"}
              </button>
            )}
            {brief.followUpDate && !brief.followUpDone && (
              <button onClick={()=>onUpdate(brief.id,{followUpDate:"",followUpDone:false})} style={{background:"none",border:"none",color:"var(--text-3)",cursor:"pointer",fontSize:12,fontFamily:"var(--font)"}}>Clear</button>
            )}
            {isOverdue && <span className="followup-badge">Overdue</span>}
          </div>

          {/* Archive / Outcome */}
          {!isArchived ? (
            <>
              <div className="section-label">Archive Brief</div>
              <div style={{display:"flex",gap:6}}>
                {[["Landed","✓","#dcfce7","#166534"],["Passed","✗","#fee2e2","#991b1b"],["Expired","↷","#f3f4f6","#6b7280"]].map(([outcome,icon,bg,color])=>(
                  <button key={outcome} onClick={()=>onUpdate(brief.id,{status:outcome,outcome})}
                    style={{flex:1,padding:"7px 8px",borderRadius:"var(--r)",border:"1px solid var(--border)",background:"var(--bg-2)",color:"var(--text-2)",fontSize:12,cursor:"pointer",fontFamily:"var(--font)",transition:"all 0.12s"}}
                    onMouseEnter={e=>{e.currentTarget.style.background=bg;e.currentTarget.style.color=color;}}
                    onMouseLeave={e=>{e.currentTarget.style.background="var(--bg-2)";e.currentTarget.style.color="var(--text-2)";}}>
                    {icon} {outcome}
                  </button>
                ))}
              </div>
            </>
          ) : (
            <>
              <div className="section-label">Outcome</div>
              <div style={{display:"flex",gap:8,alignItems:"center",marginBottom:8}}>
                <StatusBadge status={brief.status} />
                {brief.confirmedFee && <span style={{fontSize:13,fontWeight:700,color:"#059669"}}>${Number(brief.confirmedFee).toLocaleString()}</span>}
                <button onClick={()=>onUpdate(brief.id,{status:"Active",outcome:null})}
                  style={{marginLeft:"auto",background:"none",border:"1px solid var(--border)",borderRadius:"var(--r)",padding:"4px 10px",fontSize:11,cursor:"pointer",color:"var(--text-3)",fontFamily:"var(--font)"}}>
                  Re-open
                </button>
              </div>
              {brief.outcomeNotes && <div className="info-box" style={{fontSize:13,lineHeight:1.6,color:"var(--text-2)"}}>{brief.outcomeNotes}</div>}
            </>
          )}

          <div style={{height:16}}></div>
        </div>
      </div>
    </>
  );
}

// ─── PitchEntryDrawer ─────────────────────────────────────────────────────────

const PITCH_ENTRY_STAGES = ["Not Contacted","Pitched","Following Up","In Discussion","Signed","Passed","No Response"];

const PITCH_HISTORY_TYPE_LABELS = {
  "Pitched":          "Pitched",
  "Follow-Up Sent":   "Follow-Up Sent",
  "Status Changed":   "Status Changed",
  "Note":             "Note",
};

function PitchEntryDrawer({ entry, campaign, contact, onClose, onUpdate, onDelete, isCentered, onToggleCenter }) {
  if (!entry) return null;

  const [customNote,   setCustomNote]   = useState(entry.customNote || "");
  const [followUpDate, setFollowUpDate] = useState(entry.followUpDate || null);
  const [emailTab,     setEmailTab]     = useState("pitch"); // "pitch" | "followup"

  // Sync local state when entry changes
  useEffect(() => {
    setCustomNote(entry.customNote || "");
    setFollowUpDate(entry.followUpDate || null);
  }, [entry.id]);

  const contactName = contact?.name || "Unknown";
  const agencyName  = contact?.agency || contact?.type || "";

  // Overdue check
  const isOverdue = (() => {
    if (!entry.followUpDate || entry.followUpDone) return false;
    if (["Signed","Passed","No Response"].includes(entry.status)) return false;
    const d = new Date(entry.followUpDate); d.setHours(0,0,0,0);
    const t = new Date();                   t.setHours(0,0,0,0);
    return d < t;
  })();

  // Email template rendering
  const renderTemplate = (templateObj) => {
    if (!templateObj) return "";
    const body = templateObj.body || "";
    return body
      .replace(/\{\{contactName\}\}/g, contactName)
      .replace(/\{\{customNote\}\}/g, customNote || "");
  };

  const pitchRendered   = renderTemplate(campaign?.pitchTemplate);
  const followupRendered = renderTemplate(campaign?.followUpTemplate);
  const activeRendered  = emailTab === "pitch" ? pitchRendered : followupRendered;

  const handleCopy = () => {
    if (activeRendered) navigator.clipboard.writeText(activeRendered).catch(() => {});
  };

  const handleStatusChange = (newStatus) => {
    onUpdate(entry.campaignId, entry.id, { status: newStatus });
  };

  const handleFollowUpDateChange = (val) => {
    setFollowUpDate(val);
    onUpdate(entry.campaignId, entry.id, { followUpDate: val, followUpDone: false });
  };

  const handleFollowUpDoneToggle = () => {
    const newDone = !entry.followUpDone;
    onUpdate(entry.campaignId, entry.id, { followUpDone: newDone });
  };

  const handleNoteBlur = () => {
    if (customNote !== entry.customNote) {
      onUpdate(entry.campaignId, entry.id, { customNote });
    }
  };

  const handleDelete = () => {
    if (window.confirm(`Remove ${contactName} from this campaign? This cannot be undone.`)) {
      onDelete(entry.campaignId, entry.id);
      onClose();
    }
  };

  // Sorted pitch history (newest first)
  const history = [...(entry.pitchHistory || [])].sort((a, b) => new Date(b.date) - new Date(a.date));

  const inp = {
    width:"100%", padding:"6px 9px", borderRadius:6, border:"1px solid var(--border)",
    background:"var(--bg)", color:"var(--text)", fontSize:13, fontFamily:"var(--font)", outline:"none",
    boxSizing:"border-box",
  };
  const sectionLabel = {
    fontSize:9.5, color:"var(--text-3)", textTransform:"uppercase", letterSpacing:"0.07em",
    fontWeight:500, marginBottom:6, display:"block", marginTop:16,
  };

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className={isCentered ? "drawer centered" : "drawer"}>

        {/* Header */}
        <div className="drawer-header">
          <div style={{ flex:1, minWidth:0 }}>
            <div className="drawer-title" style={{ overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>
              {contactName}
            </div>
            {agencyName && (
              <div style={{ fontSize:12, color:"var(--text-3)", marginTop:2 }}>{agencyName}</div>
            )}
          </div>
          <div style={{ display:"flex", gap:6, flexShrink:0, alignItems:"center" }}>
            <span style={{
              fontSize:10.5, fontWeight:600, padding:"2px 8px", borderRadius:4,
              background: entry.status === "Signed" ? "var(--accent-dim)" : "var(--bg-2)",
              color:       entry.status === "Signed" ? "var(--accent-text)" : "var(--text-3)",
              border:      entry.status === "Signed" ? "1px solid var(--accent)" : "1px solid var(--border)",
            }}>{entry.status || "Not Contacted"}</span>
            <button className="icon-btn" onClick={onToggleCenter} title={isCentered ? "Dock to side" : "Float to center"} style={{ fontSize:13 }}>{isCentered ? "⊟" : "⊡"}</button>
            <button className="icon-btn" onClick={onClose}>✕</button>
          </div>
        </div>

        <div style={{ padding:"16px 20px", overflowY:"auto", flex:1 }}>

          {/* Status */}
          <div style={{ marginBottom:14 }}>
            <span style={sectionLabel}>Status</span>
            <select
              value={entry.status || "Not Contacted"}
              onChange={e => handleStatusChange(e.target.value)}
              style={{ ...inp, width:"auto" }}
            >
              {PITCH_ENTRY_STAGES.map(s => <option key={s}>{s}</option>)}
            </select>
          </div>

          {/* Follow-up */}
          <div style={{ marginBottom:14 }}>
            <span style={sectionLabel}>Follow-Up</span>
            <div style={{ display:"flex", gap:8, alignItems:"center", flexWrap:"wrap" }}>
              <input
                type="date"
                value={followUpDate || ""}
                onChange={e => handleFollowUpDateChange(e.target.value)}
                style={{ ...inp, width:160, color: entry.followUpDone ? "var(--text-3)" : "var(--text)" }}
              />
              {followUpDate && (
                <button
                  onClick={handleFollowUpDoneToggle}
                  style={{
                    padding:"5px 11px", borderRadius:"var(--r)", border:"1px solid var(--border)",
                    background: entry.followUpDone ? "#dcfce7" : "var(--bg-2)",
                    color:      entry.followUpDone ? "#166534" : "var(--text-2)",
                    fontSize:12, cursor:"pointer", fontFamily:"var(--font)", transition:"all 0.12s",
                  }}
                >{entry.followUpDone ? "✓ Done" : "Mark Done"}</button>
              )}
              {followUpDate && !entry.followUpDone && (
                <button onClick={() => handleFollowUpDateChange(null)} style={{ background:"none", border:"none", color:"var(--text-3)", cursor:"pointer", fontSize:12, fontFamily:"var(--font)" }}>Clear</button>
              )}
            </div>
            {isOverdue && (
              <div style={{ marginTop:6, fontSize:12, color:"#dc2626", fontWeight:500, display:"flex", alignItems:"center", gap:4 }}>
                <span>⚠</span> Follow-up is overdue
              </div>
            )}
          </div>

          {/* Notes */}
          <div style={{ marginBottom:14 }}>
            <span style={sectionLabel}>Custom Note for Email</span>
            <textarea
              value={customNote}
              onChange={e => setCustomNote(e.target.value)}
              onBlur={handleNoteBlur}
              placeholder="A personal note to include in your pitch email…"
              style={{ ...inp, minHeight:72, resize:"vertical", lineHeight:1.55 }}
            />
          </div>

          {/* Email Preview */}
          <div style={{ marginBottom:14 }}>
            <span style={sectionLabel}>Email Preview</span>
            <div style={{ display:"flex", gap:0, marginBottom:8, border:"1px solid var(--border)", borderRadius:6, overflow:"hidden" }}>
              {[["pitch","Pitch Email"],["followup","Follow-up Email"]].map(([id, label]) => (
                <button
                  key={id}
                  onClick={() => setEmailTab(id)}
                  style={{
                    flex:1, padding:"6px 0", fontSize:12, fontWeight: emailTab === id ? 600 : 400,
                    background: emailTab === id ? "var(--accent-dim)" : "var(--bg-2)",
                    color:      emailTab === id ? "var(--accent-text)" : "var(--text-3)",
                    border:"none", cursor:"pointer", fontFamily:"var(--font)", transition:"background 0.1s",
                  }}
                >{label}</button>
              ))}
            </div>
            <pre style={{
              background:"var(--bg-2)", border:"1px solid var(--border)", borderRadius:6,
              padding:"12px 14px", fontSize:12, fontFamily:"monospace", lineHeight:1.65,
              whiteSpace:"pre-wrap", wordBreak:"break-word", color:"var(--text-2)",
              maxHeight:220, overflowY:"auto", margin:0,
            }}>
              {activeRendered || <span style={{ color:"var(--text-3)", fontStyle:"italic" }}>No template set for this campaign yet.</span>}
            </pre>
            <div style={{ display:"flex", gap:6, marginTop:8 }}>
              <div style={{ position:"relative", flex:1 }}>
                <button
                  disabled
                  title="Email sending requires SendGrid setup (Step 6)"
                  style={{ width:"100%", padding:"6px 12px", borderRadius:"var(--r)", border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-3)", fontSize:12, cursor:"not-allowed", fontFamily:"var(--font)", opacity:0.55 }}
                >Send</button>
              </div>
              <button
                onClick={handleCopy}
                style={{ padding:"6px 14px", borderRadius:"var(--r)", border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-2)", fontSize:12, cursor:"pointer", fontFamily:"var(--font)", transition:"background 0.1s" }}
                onMouseEnter={e => e.currentTarget.style.background = "var(--bg)"}
                onMouseLeave={e => e.currentTarget.style.background = "var(--bg-2)"}
              >Copy to Clipboard</button>
            </div>
          </div>

          {/* Disco */}
          <div style={{ marginBottom:14 }}>
            <span style={sectionLabel}>Disco</span>
            <button
              disabled
              title="Disco integration coming soon"
              style={{ padding:"6px 14px", borderRadius:"var(--r)", border:"1px solid var(--border)", background:"var(--bg-2)", color:"var(--text-3)", fontSize:12, cursor:"not-allowed", fontFamily:"var(--font)", opacity:0.55 }}
            >Pitch via Disco</button>
          </div>

          {/* Pitch History */}
          <div style={{ marginBottom:14 }}>
            <span style={sectionLabel}>Pitch History ({history.length})</span>
            {history.length === 0 ? (
              <div style={{ fontSize:13, color:"var(--text-3)", padding:"10px 0" }}>No activity yet.</div>
            ) : (
              <div style={{ display:"flex", flexDirection:"column", gap:1, border:"1px solid var(--border)", borderRadius:8, overflow:"hidden" }}>
                {history.map((evt, i) => (
                  <div key={i} style={{ padding:"10px 13px", borderBottom: i < history.length - 1 ? "1px solid var(--border-sub)" : "none", background:"var(--card)" }}>
                    <div style={{ display:"flex", alignItems:"center", gap:6, marginBottom:evt.note ? 4 : 0 }}>
                      <span style={{ fontSize:11, color:"var(--text-3)" }}>
                        {evt.date ? new Date(evt.date).toLocaleDateString("en-AU", { day:"numeric", month:"short", year:"numeric" }) : "—"}
                      </span>
                      <span style={{ fontSize:11, fontWeight:600, color:"var(--text-2)" }}>
                        {PITCH_HISTORY_TYPE_LABELS[evt.type] || evt.type}
                      </span>
                      {evt.sentVia && (
                        <span style={{ fontSize:9.5, padding:"1px 6px", borderRadius:3, background:"var(--bg-2)", color:"var(--text-3)", border:"1px solid var(--border)" }}>{evt.sentVia}</span>
                      )}
                    </div>
                    {evt.note && (
                      <div style={{ fontSize:12, color:"var(--text-2)", lineHeight:1.5 }}>{evt.note}</div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Delete */}
          <div style={{ marginTop:24, paddingTop:16, borderTop:"1px solid var(--border)" }}>
            <button
              onClick={handleDelete}
              style={{ padding:"7px 14px", borderRadius:"var(--r)", border:"1px solid #fca5a5", background:"#fff1f1", color:"#dc2626", fontSize:12, cursor:"pointer", fontFamily:"var(--font)", fontWeight:500, transition:"all 0.1s" }}
              onMouseEnter={e => { e.currentTarget.style.background="#fee2e2"; }}
              onMouseLeave={e => { e.currentTarget.style.background="#fff1f1"; }}
            >Remove from Campaign</button>
          </div>

          <div style={{ height:16 }}></div>
        </div>
      </div>
    </>
  );
}

// ─── AddContactModal ──────────────────────────────────────────────────────────

function AddContactModal({ contacts, pitchEntries, campaignId, onAdd, onClose }) {
  const [search, setSearch] = useState("");

  const alreadyAdded = new Set((pitchEntries || []).map(e => e.contactId));
  const available = (contacts || []).filter(c => !alreadyAdded.has(c.id));

  const filtered = search.trim()
    ? available.filter(c => c.name.toLowerCase().includes(search.trim().toLowerCase()))
    : available;

  const handleSelect = (contact) => {
    const entry = {
      id: String(Date.now()),
      contactId:    contact.id,
      campaignId,
      status:       "Not Contacted",
      customNote:   "",
      followUpDate: null,
      followUpDone: false,
      pitchHistory: [],
      createdAt:    Date.now(),
      updatedAt:    Date.now(),
    };
    onAdd(campaignId, entry);
    onClose();
  };

  return (
    <>
      <div className="overlay" onClick={onClose}></div>
      <div className="drawer centered" style={{ width:420, maxHeight:"75vh", display:"flex", flexDirection:"column" }}>
        <div className="drawer-header">
          <div className="drawer-title">Add Contact to Campaign</div>
          <button className="icon-btn" onClick={onClose}>✕</button>
        </div>
        <div style={{ padding:"14px 20px 6px" }}>
          <input
            type="text"
            placeholder="Search contacts…"
            value={search}
            onChange={e => setSearch(e.target.value)}
            autoFocus
            style={{ width:"100%", padding:"7px 10px", border:"1px solid var(--border)", borderRadius:6, background:"var(--bg-2)", color:"var(--text)", fontSize:13, fontFamily:"var(--font)", outline:"none", boxSizing:"border-box" }}
          />
        </div>
        <div style={{ flex:1, overflowY:"auto", padding:"6px 0 16px" }}>
          {available.length === 0 ? (
            <div style={{ padding:"24px 20px", textAlign:"center", color:"var(--text-3)", fontSize:13 }}>
              All contacts are already in this campaign.
            </div>
          ) : filtered.length === 0 ? (
            <div style={{ padding:"24px 20px", textAlign:"center", color:"var(--text-3)", fontSize:13 }}>
              No contacts match your search.
            </div>
          ) : (
            filtered.map(contact => {
              const initials = contact.name.split(" ").filter(Boolean).map(w => w[0]).join("").slice(0, 2).toUpperCase();
              return (
                <div
                  key={contact.id}
                  onClick={() => handleSelect(contact)}
                  style={{ display:"flex", alignItems:"center", gap:10, padding:"10px 20px", cursor:"pointer", transition:"background 0.08s" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                >
                  <div style={{ width:32, height:32, borderRadius:7, background:"var(--accent-dim)", color:"var(--accent-text)", display:"flex", alignItems:"center", justifyContent:"center", fontWeight:700, fontSize:11, flexShrink:0 }}>
                    {initials}
                  </div>
                  <div>
                    <div style={{ fontSize:13, fontWeight:500, color:"var(--text)" }}>{contact.name}</div>
                    {(contact.agency || contact.type) && (
                      <div style={{ fontSize:11, color:"var(--text-3)", marginTop:1 }}>{contact.agency || contact.type}</div>
                    )}
                  </div>
                </div>
              );
            })
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { Badge, StatusBadge, BriefOutcomeBadge, EmbedPlayer, SongDrawer, BriefDrawer, NewBriefModal, CollabDrawer, PublisherDrawer, ArtistDrawer, ContactDrawer, TweaksPanel, TWEAK_DEFAULTS, PUB_TYPE_COLORS, CommandPalette, NewSongModal, NotificationsPanel, PitchEntryDrawer, AddContactModal });
