// Company detail drawer — overview, touchpoints, tasks, events, contacts + edit
function ClientDrawer({ open, data, onClose }){
  const [tab, setTab] = React.useState("overview");
  const [newType, setNewType] = React.useState("call");
  const [newNote, setNewNote] = React.useState("");
  const [newTaskTitle, setNewTaskTitle] = React.useState("");
  const [editOpen, setEditOpen] = React.useState(false);

  // Subscribe to store so live edits / new tasks / events reflect in the drawer
  const storeState = window.useStore(s => s);
  // Live Operations Roadmap data — MUST be called unconditionally on every render,
  // before any early return, to satisfy React's Rules of Hooks.
  const liveHook = window.useRoadmap ? window.useRoadmap() : null;

  React.useEffect(()=>{
    if(data){
      setTab(data._initialTab || "overview");
      setEditOpen(false);
    }
  }, [data?.name, data?.segment, data?._initialTab, data?._highlightTaskAt]);

  React.useEffect(()=>{
    const onKey = (e) => { if(e.key === "Escape" && open && !editOpen) onClose(); };
    window.addEventListener("keydown", onKey);
    return ()=>window.removeEventListener("keydown", onKey);
  }, [open, onClose, editOpen]);

  if(!data) return null;

  // Resolve overrides + logo from store
  const segment = data.segment || "md";
  const baseTable = segment === "mgmt" ? MGMT_DATA : MD_DATA;
  const baseData = baseTable[data.name] || data;
  const resolved = resolveCompany(data.name, segment, baseData);
  const logo = resolved.logo;
  const displayName = resolved.displayName;
  const merged = { ...data, ...resolved.data };

  // Tasks live in the store now
  const storeTasks = window.Store ? window.Store.getTasks(data.name, segment) : null;
  const tasks = storeTasks !== null ? storeTasks : (merged.tasks || []);
  const setTasks = (next) => window.Store && window.Store.setTasks(data.name, segment, next);

  // Touchpoints live in the store
  const storeTPs = window.Store ? window.Store.getTouchpoints(data.name, segment) : null;
  const touchpoints = storeTPs !== null ? storeTPs : (merged.timeline || []);
  const setTouchpoints = (next) => window.Store && window.Store.setTouchpoints(data.name, segment, next);

  // Events for this company come from the live Operations Roadmap (Monday board).
  // (liveHook was resolved above the early return — see Rules of Hooks comment.)
  const liveLane = liveHook && liveHook.data
    ? liveHook.data.lanes.find(l => (l.name || "").toLowerCase() === (data.name || "").toLowerCase())
    : null;
  const events = liveLane ? liveLane.bars : [];

  const segmentLabel = segment === "mgmt" ? "Management & Retainer" : "MD Service";

  const addTouchpoint = () => {
    if(!newNote.trim()) return;
    setTouchpoints([{ type:newType, who:"Dr. Yohai", date:"Just now", title:newType==="call"?"Call":newType==="email"?"Email":"Meeting", note:newNote }, ...touchpoints]);
    setNewNote("");
  };
  const addTask = () => {
    if(!newTaskTitle.trim()) return;
    setTasks([...tasks, { title:newTaskTitle, due:"No date", status:"", done:false, addedAt: Date.now() }]);
    setNewTaskTitle("");
  };
  const toggleTask = (i) => {
    const cp = [...tasks];
    cp[i] = { ...cp[i], done: !cp[i].done };
    setTasks(cp);
  };

  const champ = merged.champion || merged.poc;

  return (
    <React.Fragment>
      <div className={"drawer-scrim " + (open ? "on":"")} onClick={onClose}/>
      <aside className={"drawer " + (open ? "on":"")}>
        <div className="dr-head">
          <div className="logo" style={{ background: logo.bg }}><CompanyGlyph name={data.name} size={28} override={logo}/></div>
          <div className="ti">
            <span className="eyebrow">{segmentLabel}</span>
            <h2>
              <EditableText
                value={displayName}
                onSave={(v)=>window.Store && window.Store.setCompanyOverride(data.name, segment, { _displayName: v })}
                ariaLabel="Company name"
              />
            </h2>
            <div className="row">
              {champ && <span><Icon.Users/> {champ.name} · {champ.role}</span>}
              <span><Icon.Money/>
                {" "}
                <EditableText
                  value={merged.mrr}
                  onSave={(v)=>window.Store && window.Store.setCompanyOverride(data.name, segment, { mrr: v })}
                  ariaLabel="MRR"
                />/mo
              </span>
              <span><Icon.Calendar/> Renews{" "}
                <EditableText
                  value={merged.renewalDate}
                  onSave={(v)=>window.Store && window.Store.setCompanyOverride(data.name, segment, { renewalDate: v })}
                  ariaLabel="Renewal date"
                />
              </span>
            </div>
          </div>
          <button className="dr-edit" onClick={()=>setEditOpen(true)} title="Edit logo, champion, segment, MRR…">
            <Icon.Pencil/> <span>Edit</span>
          </button>
          <button className="dr-close" onClick={onClose} title="Close"><Icon.Close/></button>
        </div>

        <div className="dr-tabs">
          <button className={"dr-tab " + (tab==="overview"?"on":"")} onClick={()=>setTab("overview")}>Overview</button>
          <button className={"dr-tab " + (tab==="touchpoints"?"on":"")} onClick={()=>setTab("touchpoints")}>Touchpoints</button>
          <button className={"dr-tab " + (tab==="tasks"?"on":"")} onClick={()=>setTab("tasks")}>Tasks ({tasks.filter(t=>!t.done).length})</button>
          <button className={"dr-tab " + (tab==="events"?"on":"")} onClick={()=>setTab("events")}>Events ({events.length})</button>
          <button className={"dr-tab " + (tab==="contacts"?"on":"")} onClick={()=>setTab("contacts")}>Contacts</button>
        </div>

        <div className="dr-body">
          {tab === "overview" && (
            <DrawerOverview merged={merged} logo={logo} tasks={tasks}/>
          )}

          {tab === "touchpoints" && (
            <DrawerTouchpoints
              touchpoints={touchpoints}
              setTouchpoints={setTouchpoints}
              newType={newType} setNewType={setNewType}
              newNote={newNote} setNewNote={setNewNote}
              addTouchpoint={addTouchpoint}
            />
          )}

          {tab === "tasks" && (
            <DrawerTasks
              data={merged} displayName={displayName}
              tasks={tasks} setTasks={setTasks} toggleTask={toggleTask}
              newTaskTitle={newTaskTitle} setNewTaskTitle={setNewTaskTitle}
              addTask={addTask}
              highlightTaskAt={data._highlightTaskAt}
            />
          )}

          {tab === "events" && (
            <RoadmapEventsPanel companyName={data.name}/>
          )}

          {tab === "contacts" && (
            <DrawerContacts data={merged} displayName={displayName} clientName={data.name} segment={segment}/>
          )}
        </div>
      </aside>

      {editOpen && (
        <EditCompanyModal
          clientName={data.name}
          segment={segment}
          base={merged}
          currentLogo={logo}
          onClose={()=>setEditOpen(false)}
        />
      )}
    </React.Fragment>
  );
}

// ===== Tab content components =====
function DrawerOverview({ merged, logo, tasks }){
  const initials = (n) => (n||"").split(" ").map(w=>w[0]).slice(0,2).join("");
  return (
    <React.Fragment>
      {merged.champion && (
        <div className="dr-section">
          <h4>Our champion at {merged.name || ""}</h4>
          <div className="champ-card">
            <div className="champ-av" style={{ background: logo.bg }}>{initials(merged.champion.name)}</div>
            <div className="champ-info">
              <div className="champ-top">
                <b>{merged.champion.name}</b>
                <span className={"champ-rel " + (merged.champion.relationship||"")}>{merged.champion.relationship} relationship</span>
              </div>
              <div className="champ-role">{merged.champion.role}</div>
              <div className="champ-meta">
                <span><Icon.Mail/> {merged.champion.email}</span>
                <span><Icon.Phone/> {merged.champion.phone}</span>
                <span><Icon.Calendar/> Since {merged.champion.since}</span>
              </div>
              <p className="champ-note">{merged.champion.note}</p>
            </div>
          </div>
        </div>
      )}

      <div className="dr-section">
        <h4>Current project</h4>
        <div className="dr-card highlight">
          <div className="k">In progress</div>
          <div className="v">{merged.currentProject}</div>
        </div>
      </div>

      <div className="dr-section">
        <h4>Last touchpoint</h4>
        <div className="dr-card">
          <div className="k">{(merged.lastTouch?.type||"").toUpperCase()} · {merged.lastTouch?.who} · {merged.lastTouch?.when}</div>
          <div className="v">{merged.lastTouch?.note}</div>
        </div>
      </div>

      <div className="dr-section">
        <h4>Opportunity to expand</h4>
        <div className="opp">
          <div className="head">
            <b>Expansion signal</b>
            <span className="v">+{(merged.opportunity||"").match(/₪[\d.,]+[KM]?/)?.[0] || "—"}</span>
          </div>
          <p>{merged.opportunity}</p>
        </div>
      </div>

      <div className="dr-section">
        <h4>Contract renewal</h4>
        <div className="renewal">
          <div className="head">
            <b>{merged.renewalDate}</b>
            <span className={"days " + (merged.renewalDays < 15 ? "overdue" : merged.renewalDays < 60 ? "soon" : "")}>
              {merged.renewalDays} days out
            </span>
          </div>
          <div className="bar"><div style={{ width: Math.min(100, 100 - (merged.renewalDays/365)*100) + "%" }}/></div>
          <div className="timeline">
            <span>Today</span>
            <span>Renewal</span>
          </div>
        </div>
      </div>

      <div className="dr-section">
        <h4>Next call</h4>
        <div className="dr-kv">
          <div className="dr-card">
            <div className="k">Scheduled</div>
            <div className="v">{merged.nextCall}</div>
          </div>
          <div className="dr-card">
            <div className="k">Open tasks</div>
            <div className="v">{tasks.filter(t=>!t.done).length} · {tasks.filter(t=>t.status==="overdue"&&!t.done).length} overdue</div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

function DrawerTouchpoints({ touchpoints, setTouchpoints, newType, setNewType, newNote, setNewNote, addTouchpoint }){
  const [editingIdx, setEditingIdx] = React.useState(null);
  const [editForm, setEditForm] = React.useState({ type:"call", title:"", note:"" });

  const startEdit = (i, t) => {
    setEditingIdx(i);
    setEditForm({ type: t.type || "call", title: t.title || "", note: t.note || "" });
  };
  const saveEdit = () => {
    const cp = [...touchpoints];
    cp[editingIdx] = {
      ...cp[editingIdx],
      type: editForm.type,
      title: editForm.title || (editForm.type==="call"?"Call":editForm.type==="email"?"Email":"Meeting"),
      note: editForm.note,
    };
    setTouchpoints(cp);
    setEditingIdx(null);
  };
  const removeAt = (i) => {
    if(!confirm("Delete this touchpoint?")) return;
    setTouchpoints(touchpoints.filter((_, idx) => idx !== i));
    if(editingIdx === i) setEditingIdx(null);
  };

  return (
    <React.Fragment>
      <div className="dr-section">
        <h4>Add a touchpoint</h4>
        <div className="dr-form">
          <div className="seg">
            <button className={newType==="call"?"on":""} onClick={()=>setNewType("call")}>Call</button>
            <button className={newType==="email"?"on":""} onClick={()=>setNewType("email")}>Email</button>
            <button className={newType==="meet"?"on":""} onClick={()=>setNewType("meet")}>Meeting</button>
          </div>
          <textarea placeholder="What happened? What did they say?" value={newNote} onChange={e=>setNewNote(e.target.value)} />
          <button className="btn-submit" onClick={addTouchpoint}>
            <Icon.Plus/> Log touchpoint
          </button>
        </div>
      </div>

      <div className="dr-section">
        <h4>Timeline</h4>
        <div className="tp">
          {touchpoints.map((t, i)=>(
            <div key={i} className="tp-item">
              <div className={"tp-dot " + t.type}>
                {t.type==="call" && <Icon.Phone/>}
                {t.type==="email" && <Icon.Mail/>}
                {t.type==="meet" && <Icon.Users/>}
              </div>
              {editingIdx === i ? (
                <div className="tp-body editing">
                  <div className="seg" style={{marginBottom:8}}>
                    <button className={editForm.type==="call"?"on":""} onClick={()=>setEditForm({...editForm,type:"call"})}>Call</button>
                    <button className={editForm.type==="email"?"on":""} onClick={()=>setEditForm({...editForm,type:"email"})}>Email</button>
                    <button className={editForm.type==="meet"?"on":""} onClick={()=>setEditForm({...editForm,type:"meet"})}>Meeting</button>
                  </div>
                  <input className="tp-edit-title" value={editForm.title}
                         placeholder="Title (optional)"
                         onChange={e=>setEditForm({...editForm, title:e.target.value})}/>
                  <textarea className="tp-edit-note" value={editForm.note}
                            placeholder="What happened?"
                            onChange={e=>setEditForm({...editForm, note:e.target.value})}
                            rows={3}/>
                  <div className="dr-form-actions">
                    <button className="btn-ghost" onClick={()=>setEditingIdx(null)}>Cancel</button>
                    <button className="btn-primary" onClick={saveEdit}>Save</button>
                  </div>
                </div>
              ) : (
                <div className="tp-body">
                  <div className="head">
                    <b>{t.title}</b>
                    <time>{t.date}</time>
                    <div className="tp-actions">
                      <button title="Edit" onClick={()=>startEdit(i, t)}><Icon.Pencil/></button>
                      <button title="Delete" onClick={()=>removeAt(i)}><Icon.Trash/></button>
                    </div>
                  </div>
                  <p>{t.note}</p>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </React.Fragment>
  );
}

function DrawerTasks({ data, displayName, tasks, setTasks, toggleTask, newTaskTitle, setNewTaskTitle, addTask, highlightTaskAt }){
  const [editingIdx, setEditingIdx] = React.useState(null);
  const [editForm, setEditForm] = React.useState({ title:"", due:"", status:"", link:"" });
  const [flashIdx, setFlashIdx] = React.useState(null);
  const taskRefs = React.useRef({});

  // Add-task form state — persisted across renders within drawer session
  const [addTitle, setAddTitle] = React.useState("");
  const [addDate, setAddDate] = React.useState("");
  const [addTime, setAddTime] = React.useState("");
  const [addStatus, setAddStatus] = React.useState("");
  const [addLink, setAddLink] = React.useState("");
  const [addExpanded, setAddExpanded] = React.useState(false);

  // Scroll-into-view + flash highlight when a task is opened from "What needs attention".
  React.useEffect(() => {
    if (!highlightTaskAt) return;
    const idx = tasks.findIndex(t => t.addedAt === highlightTaskAt);
    if (idx < 0) return;
    const el = taskRefs.current[idx];
    if (el && el.scrollIntoView) el.scrollIntoView({ behavior: "smooth", block: "center" });
    setFlashIdx(idx);
    const t = setTimeout(() => setFlashIdx(null), 1800);
    return () => clearTimeout(t);
  }, [highlightTaskAt, tasks.length]);

  const formatDue = (dateStr, timeStr) => {
    if(!dateStr) return "No date";
    try {
      const d = new Date(dateStr + (timeStr ? "T" + timeStr : "T00:00"));
      if(isNaN(d.getTime())) return "No date";
      const today = new Date(); today.setHours(0,0,0,0);
      const target = new Date(d); target.setHours(0,0,0,0);
      const diff = Math.round((target - today) / 86400000);
      const dateLabel =
        diff === 0 ? "Today" :
        diff === 1 ? "Tomorrow" :
        diff === -1 ? "Yesterday" :
        diff > 1 && diff < 7 ? d.toLocaleDateString(undefined, { weekday:"long" }) :
        d.toLocaleDateString(undefined, { month:"short", day:"numeric" });
      if(timeStr){
        const tm = d.toLocaleTimeString(undefined, { hour:"numeric", minute:"2-digit" });
        return dateLabel + " · " + tm;
      }
      return dateLabel;
    } catch(e){ return "No date"; }
  };

  const inferStatus = (dateStr) => {
    if(!dateStr) return "";
    const d = new Date(dateStr + "T00:00");
    const today = new Date(); today.setHours(0,0,0,0);
    const diff = Math.round((d - today) / 86400000);
    if(diff < 0) return "overdue";
    if(diff <= 3) return "soon";
    return "";
  };

  const submitAdd = () => {
    const title = addTitle.trim();
    if(!title) return;
    const status = addStatus || inferStatus(addDate);
    const due = formatDue(addDate, addTime);
    setTasks([...tasks, {
      title, due, status, done:false, addedAt: Date.now(),
      dueIso: addDate || null, dueTime: addTime || null,
      link: addLink.trim() || null,
    }]);
    setAddTitle(""); setAddDate(""); setAddTime(""); setAddStatus(""); setAddLink("");
    setAddExpanded(false);
  };

  const startEdit = (i, t) => {
    setEditingIdx(i);
    setEditForm({
      title: t.title || "",
      due: t.due || "",
      status: t.status || "",
      dueIso: t.dueIso || "",
      dueTime: t.dueTime || "",
      link: t.link || "",
    });
  };
  const saveEdit = () => {
    const cp = [...tasks];
    const dueText = editForm.dueIso ? formatDue(editForm.dueIso, editForm.dueTime) : (editForm.due || "No date");
    cp[editingIdx] = {
      ...cp[editingIdx],
      title: editForm.title,
      due: dueText,
      status: editForm.status,
      dueIso: editForm.dueIso || null,
      dueTime: editForm.dueTime || null,
      link: (editForm.link || "").trim() || null,
    };
    setTasks(cp);
    setEditingIdx(null);
  };
  const removeAt = (i) => {
    if(!confirm("Delete this task?")) return;
    setTasks(tasks.filter((_, idx) => idx !== i));
    if(editingIdx === i) setEditingIdx(null);
  };

  const STATUS_PILLS = [
    { k:"", label:"None" },
    { k:"soon", label:"Soon" },
    { k:"overdue", label:"Overdue" },
  ];

  return (
    <React.Fragment>
      <div className="dr-section">
        <h4>Add a task</h4>
        <div className="dr-form add-task-form">
          <div className="row-in">
            <input
              placeholder="What needs doing?"
              value={addTitle}
              onChange={e=>setAddTitle(e.target.value)}
              onFocus={()=>setAddExpanded(true)}
              onKeyDown={e=>{
                if(e.key==='Enter' && (e.metaKey || e.ctrlKey || !addExpanded)) submitAdd();
                if(e.key==='Escape'){ setAddExpanded(false); }
              }}
            />
            {!addExpanded && (
              <button className="btn-submit" onClick={()=>{ if(addTitle.trim()) submitAdd(); else setAddExpanded(true); }}>
                <Icon.Plus/>
              </button>
            )}
          </div>

          {addExpanded && (
            <div className="add-task-details">
              <div className="bf-row two">
                <div className="bf-field">
                  <label><Icon.Calendar/> Date</label>
                  <input type="date" value={addDate} onChange={e=>setAddDate(e.target.value)}/>
                </div>
                <div className="bf-field">
                  <label>Time <span className="bf-optional">(optional)</span></label>
                  <input type="time" value={addTime} onChange={e=>setAddTime(e.target.value)}/>
                </div>
              </div>
              <div className="add-task-quick">
                <span className="add-task-quick-label">Quick:</span>
                <button type="button" onClick={()=>{
                  const d = new Date(); setAddDate(d.toISOString().slice(0,10));
                }}>Today</button>
                <button type="button" onClick={()=>{
                  const d = new Date(); d.setDate(d.getDate()+1); setAddDate(d.toISOString().slice(0,10));
                }}>Tomorrow</button>
                <button type="button" onClick={()=>{
                  const d = new Date();
                  const day = d.getDay();
                  const offset = day <= 5 ? (5 - day) : (12 - day); // next Friday
                  d.setDate(d.getDate() + offset);
                  setAddDate(d.toISOString().slice(0,10));
                }}>Friday</button>
                <button type="button" onClick={()=>{
                  const d = new Date(); d.setDate(d.getDate()+7); setAddDate(d.toISOString().slice(0,10));
                }}>Next week</button>
              </div>
              <div className="bf-field">
                <label>Urgency</label>
                <div className="bf-status-pick">
                  {STATUS_PILLS.map(s => (
                    <button type="button" key={s.k}
                            className={"bf-status-chip " + (addStatus===s.k?"on":"")}
                            onClick={()=>setAddStatus(s.k)}>
                      {s.label}
                    </button>
                  ))}
                  <span className="bf-status-hint">Auto from date if blank</span>
                </div>
              </div>
              <div className="bf-field">
                <label>Link <span className="bf-optional">(optional)</span></label>
                <input type="url" value={addLink}
                       placeholder="https://… (Monday item, doc, email thread, anything)"
                       onChange={e=>setAddLink(e.target.value)}/>
              </div>
              <div className="dr-form-actions">
                <button className="btn-ghost" onClick={()=>{
                  setAddTitle(""); setAddDate(""); setAddTime(""); setAddStatus(""); setAddLink("");
                  setAddExpanded(false);
                }}>Cancel</button>
                <button className="btn-primary" onClick={submitAdd} disabled={!addTitle.trim()}>
                  Add task{addDate ? " · " + formatDue(addDate, addTime) : ""}
                </button>
              </div>
            </div>
          )}
          {!addExpanded && <span className="dr-hint">Tasks added here count toward the home page's open tasks.</span>}
        </div>
      </div>

      <div className="dr-section">
        <h4>Open tasks ({tasks.filter(t=>!t.done).length})</h4>
        <div>
          {tasks.map((t, i)=>(
            editingIdx === i ? (
              <div key={i} className="task-edit">
                <div className="bf-field">
                  <label>Title</label>
                  <input autoFocus value={editForm.title}
                         onChange={e=>setEditForm({...editForm, title:e.target.value})}/>
                </div>
                <div className="bf-row two">
                  <div className="bf-field">
                    <label><Icon.Calendar/> Date</label>
                    <input type="date" value={editForm.dueIso || ""}
                           onChange={e=>setEditForm({...editForm, dueIso:e.target.value})}/>
                  </div>
                  <div className="bf-field">
                    <label>Time <span className="bf-optional">(optional)</span></label>
                    <input type="time" value={editForm.dueTime || ""}
                           onChange={e=>setEditForm({...editForm, dueTime:e.target.value})}/>
                  </div>
                </div>
                <div className="bf-field">
                  <label>Urgency</label>
                  <div className="bf-status-pick">
                    {STATUS_PILLS.map(s => (
                      <button key={s.k}
                              className={"bf-status-chip " + (editForm.status===s.k?"on":"")}
                              onClick={()=>setEditForm({...editForm, status:s.k})}>
                        {s.label}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="bf-field">
                  <label>Link <span className="bf-optional">(optional)</span></label>
                  <input type="url" value={editForm.link || ""}
                         placeholder="https://…"
                         onChange={e=>setEditForm({...editForm, link:e.target.value})}/>
                </div>
                <div className="dr-form-actions">
                  <button className="btn-ghost" onClick={()=>setEditingIdx(null)}>Cancel</button>
                  <button className="btn-primary" onClick={saveEdit} disabled={!editForm.title.trim()}>Save</button>
                </div>
              </div>
            ) : (
              <div key={i}
                   ref={el => { if(el) taskRefs.current[i] = el; }}
                   className={"task " + (t.done?"done":"") + (flashIdx===i ? " flash":"")}
                   style={flashIdx===i ? { boxShadow:"0 0 0 2px var(--accent)", borderRadius:8, transition:"box-shadow .8s ease" } : null}>
                <div className={"task-check " + (t.done?"done":"")} onClick={()=>toggleTask(i)}>
                  {t.done && <Icon.Check/>}
                </div>
                <div className="task-info">
                  <b>{t.title}</b>
                  <span>{displayName}</span>
                  {t.link && (
                    <a href={t.link} target="_blank" rel="noreferrer"
                       onClick={e=>e.stopPropagation()}
                       style={{
                         display:"inline-flex", alignItems:"center", gap:4,
                         marginTop:4, padding:"2px 8px", borderRadius:999,
                         background:"color-mix(in oklab, var(--accent-soft) 25%, transparent)",
                         border:"1px solid var(--accent-soft)",
                         fontSize:11, fontFamily:"'JetBrains Mono',monospace",
                         color:"var(--ink)", textDecoration:"none",
                         width:"fit-content", maxWidth:"100%",
                         overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap",
                       }}>
                      🔗 {(() => { try { return new URL(t.link).hostname.replace(/^www\./,""); } catch { return "link"; } })()}
                    </a>
                  )}
                </div>
                <span className={"task-due " + (t.status || "")}>{t.due}</span>
                <div className="task-actions">
                  <button title="Edit" onClick={()=>startEdit(i, t)}><Icon.Pencil/></button>
                  <button title="Delete" onClick={()=>removeAt(i)}><Icon.Trash/></button>
                </div>
              </div>
            )
          ))}
        </div>
      </div>
    </React.Fragment>
  );
}

// ===== Events tab =====
const STATUS_OPTIONS = [
  { k:"in-progress", label:"Active",     color:"var(--teal)" },
  { k:"planned",     label:"Planned",    color:"var(--accent)" },
  { k:"upcoming",    label:"Upcoming",   color:"var(--plum)" },
  { k:"event",       label:"Event",      color:"var(--gold)" },
  { k:"milestone",   label:"Milestone",  color:"var(--gold)" },
  { k:"overdue",     label:"Overdue",    color:"var(--red)" },
];
const STATUS_COLOR_LOOKUP = STATUS_OPTIONS.reduce((m,s)=>{ m[s.k]=s.color; return m; },{});

function DrawerEvents({ events, clientName, segment, displayName }){
  const [adding, setAdding] = React.useState(false);
  const [editingBar, setEditingBar] = React.useState(null);
  const [form, setForm] = React.useState({
    title:"", status:"planned", color:"var(--accent)", start:0, len:7, owner:"", note:"",
  });
  const set = (k,v) => setForm({...form, [k]:v});
  const setStatus = (s) => setForm({...form, status:s, color:STATUS_COLOR_LOOKUP[s] || form.color});

  const dayLabel = (offset) => {
    const dt = new Date(2026, 3, 24 + offset);
    return dt.toLocaleDateString("en-US",{month:"short",day:"numeric"});
  };

  const submit = () => {
    if(!form.title.trim()) return;
    if(!window.Store) return;
    window.Store.addBarToClient(clientName, segment, {
      title: form.title,
      status: form.status,
      color: form.color,
      start: form.start,
      len: form.status === "milestone" ? 1 : form.len,
      owner: form.owner || undefined,
      note: form.note || undefined,
      ...(form.status === "milestone" || (form.status === "event" && form.len <= 1) ? { milestone: form.start } : {}),
    });
    setForm({ title:"", status:"planned", color:"var(--accent)", start:0, len:7, owner:"", note:"" });
    setAdding(false);
  };

  // Sort events by start day asc
  const sorted = [...events].sort((a,b)=>(a.start||0)-(b.start||0));

  return (
    <React.Fragment>
      <div className="dr-section">
        <div className="dr-events-head">
          <h4>{events.length === 0 ? "No events yet" : `${events.length} event${events.length>1?"s":""} on the timeline`}</h4>
          {!adding && (
            <button className="btn-submit small" onClick={()=>setAdding(true)}>
              <Icon.Plus/> Add event
            </button>
          )}
        </div>
        <span className="dr-hint">
          Events here appear on the home page Gantt lane for {displayName} and on the calendar view.
        </span>
      </div>

      {adding && (
        <div className="dr-section">
          <div className="dr-form">
            <div className="bf-field">
              <label>Title</label>
              <input autoFocus value={form.title}
                     placeholder="e.g. Cardiac Screening Day"
                     onChange={e=>set("title", e.target.value)}/>
            </div>
            <div className="bf-field">
              <label>Status / kind</label>
              <div className="bf-status-pick">
                {STATUS_OPTIONS.map(s => (
                  <button key={s.k}
                          className={"bf-status-chip " + (form.status===s.k?"on":"")}
                          style={form.status===s.k?{background:s.color,color:"#fff",borderColor:s.color}:{}}
                          onClick={()=>setStatus(s.k)}>
                    <span className="dot" style={{background:s.color}}/>
                    {s.label}
                  </button>
                ))}
              </div>
            </div>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Start ({dayLabel(form.start)})</label>
                <input type="range" min="0" max="89" value={form.start}
                       onChange={e=>set("start", parseInt(e.target.value))}/>
              </div>
              {form.status !== "milestone" && (
                <div className="bf-field">
                  <label>Duration · {form.len} day{form.len!==1?"s":""}</label>
                  <input type="range" min="1" max="60" value={form.len}
                         onChange={e=>set("len", parseInt(e.target.value))}/>
                </div>
              )}
            </div>
            <div className="bf-field">
              <label>Owner (optional)</label>
              <input value={form.owner} placeholder="Dr. Yohai"
                     onChange={e=>set("owner", e.target.value)}/>
            </div>
            <div className="bf-field">
              <label>Notes (optional)</label>
              <textarea rows={3} value={form.note}
                        placeholder="Context, links, decisions…"
                        onChange={e=>set("note", e.target.value)}/>
            </div>
            <div className="dr-form-actions">
              <button className="btn-ghost" onClick={()=>setAdding(false)}>Cancel</button>
              <button className="btn-primary" onClick={submit} disabled={!form.title.trim()}>
                Add to timeline
              </button>
            </div>
          </div>
        </div>
      )}

      {sorted.length > 0 && (
        <div className="dr-section">
          <div className="dr-events-list">
            {sorted.map(e => (
              <div key={e.id} className="dr-event clickable" onClick={()=>setEditingBar(e)} title="Click to edit">
                <span className="dr-event-bar" style={{ background: e.color || "var(--accent)" }}/>
                <div className="dr-event-body">
                  <div className="dr-event-top">
                    <b>{e.title}</b>
                    <span className={"dr-event-status " + (e.status||"")}>{e.status}</span>
                  </div>
                  <div className="dr-event-meta">
                    <span><Icon.Calendar/> {dayLabel(e.start || 0)}{e.len > 1 ? ` — ${dayLabel((e.start||0) + e.len)}` : ""}</span>
                    {e.owner && <span><Icon.Users/> {e.owner}</span>}
                  </div>
                  {e.note && <p className="dr-event-note">{e.note}</p>}
                </div>
                <div className="dr-event-edit-hint"><Icon.Pencil/></div>
              </div>
            ))}
          </div>
        </div>
      )}

      {editingBar && window.BarDetailModal && (
        <window.BarDetailModal
          lane={{ name: displayName, segment: (segment === "mgmt" ? "MGMT" : "MD") }}
          bar={editingBar}
          isNew={false}
          onClose={()=>setEditingBar(null)}
          onSave={(patch)=>{
            window.Store.updateBarById(editingBar.id, patch);
            setEditingBar(null);
          }}
          onDelete={()=>{
            if(!confirm("Delete this event?")) return;
            window.Store.deleteBarById(editingBar.id);
            setEditingBar(null);
          }}
        />
      )}
    </React.Fragment>
  );
}

function DrawerContacts({ data, displayName, clientName, segment }){
  const colors = ["linear-gradient(135deg,#E07856,#7C3F58)","linear-gradient(135deg,#6B9B7A,#4A6E68)","linear-gradient(135deg,#D9A78E,#7C3F58)","linear-gradient(135deg,#E8B84A,#B08A2A)"];
  const initials = (n) => (n||"?").split(" ").map(w=>w[0]).slice(0,2).join("").toUpperCase();

  // Pull from store if present, else seed from merged.contacts
  const stored = window.Store ? window.Store.getContacts(clientName, segment) : null;
  const baseContacts = stored !== null ? stored : (data.contacts || []);
  const persist = (next) => {
    if(window.Store) window.Store.setContacts(clientName, segment, next);
  };

  // Auto-include the champion as the first contact (if set and not already listed by name).
  // Edits to that synthetic row route back to companyOverride.champion so the two stay in sync.
  const champ = data.champion || data.poc;
  const champInList = champ && champ.name && baseContacts.some(c =>
    (c.name||"").toLowerCase() === (champ.name||"").toLowerCase()
  );
  const championRow = (champ && champ.name && !champInList)
    ? { ...champ, _champion: true, initial: initials(champ.name) }
    : null;
  const contacts = championRow ? [championRow, ...baseContacts] : baseContacts;

  // Champion edits route to companyOverride.champion; regular contact edits to the list.
  const persistChampion = (patch) => {
    if (!window.Store) return;
    const cur = window.Store.getCompanyOverride(clientName, segment) || {};
    const nextChamp = { ...(cur.champion || champ || {}), ...patch };
    window.Store.setCompanyOverride(clientName, segment, { champion: nextChamp, poc: nextChamp });
  };
  const updateAt = (idx, patch) => {
    if (championRow && idx === 0) { persistChampion(patch); return; }
    const realIdx = championRow ? idx - 1 : idx;
    const next = baseContacts.map((c, i)=> i===realIdx ? { ...c, ...patch, initial: patch.name ? initials(patch.name) : c.initial } : c);
    persist(next);
  };
  const removeAt = (idx) => {
    if (championRow && idx === 0) return; // protect the champion row — edit/remove via "Edit company"
    const realIdx = championRow ? idx - 1 : idx;
    persist(baseContacts.filter((_, i)=> i !== realIdx));
  };
  const addNew = () => {
    persist([...baseContacts, { name:"New contact", role:"Role", initial:"NC" }]);
  };

  return (
    <div className="dr-section">
      <h4>Contacts at {displayName}</h4>
      <div>
        {contacts.map((c, i)=>(
          <div key={i} className="contact">
            <div className="av" style={{ background: colors[i % colors.length] }}>{c.initial || initials(c.name)}</div>
            <div className="info">
              <b>
                <EditableText
                  value={c.name}
                  onSave={(v)=>updateAt(i, { name: v })}
                  ariaLabel="Contact name"
                  placeholder="Name"
                />
              </b>
              <span>
                <EditableText
                  value={c.role}
                  onSave={(v)=>updateAt(i, { role: v })}
                  ariaLabel="Contact role"
                  placeholder="Role"
                />
              </span>
            </div>
            <div className="act">
              <button title="Call"><Icon.Phone/></button>
              <button title="Email"><Icon.Mail/></button>
            </div>
            <div className="inline-row-actions">
              <button title="Delete contact" onClick={()=>removeAt(i)}><Icon.Trash/></button>
            </div>
          </div>
        ))}
        <button className="inline-add-row" onClick={addNew}>
          <Icon.Plus/> Add contact
        </button>
      </div>
    </div>
  );
}

// ===== Edit company modal =====
const LOGO_PRESETS = [
  "linear-gradient(135deg,#FF3D57,#FF8A3D)",
  "linear-gradient(135deg,#2563EB,#0EA5E9)",
  "linear-gradient(135deg,#1E293B,#475569)",
  "linear-gradient(135deg,#7C3F58,#D9A78E)",
  "linear-gradient(135deg,#E07856,#F3B89E)",
  "linear-gradient(135deg,#6B9B7A,#BFD8C4)",
  "linear-gradient(135deg,#0F172A,#334155)",
  "linear-gradient(135deg,#8B5CF6,#EC4899)",
  "linear-gradient(135deg,#2A1D1A,#6B5C54)",
  "linear-gradient(135deg,#0EA5A4,#22C55E)",
  "linear-gradient(135deg,#F59E0B,#EA580C)",
  "linear-gradient(135deg,#475569,#0F172A)",
];
const HEALTH_OPTIONS = [
  { k:"green", label:"Healthy" },
  { k:"amber", label:"Watch" },
  { k:"red",   label:"At risk" },
];
const RELATIONSHIP_OPTIONS = ["new", "warm", "strong", "distant"];

function EditCompanyModal({ clientName, segment, base, currentLogo, onClose }){
  // Pull current overrides:
  //   ov       — per-engagement (segment-specific)
  //   identity — shared across segments (champion, logo, health, displayName)
  const ov       = (window.Store && window.Store.getCompanyOverride) ? (window.Store.getCompanyOverride(clientName, segment) || {}) : {};
  const identity = (window.Store && window.Store.getCompanyIdentity) ? (window.Store.getCompanyIdentity(clientName) || {}) : {};
  // Helper: identity wins over per-engagement override which wins over the mock seed.
  const seed = (k, fallback) => (identity[k] != null ? identity[k] : (ov[k] != null ? ov[k] : (base[k] != null ? base[k] : fallback)));
  const champSeed = identity.champion || base.champion || base.poc || {};

  const [form, setForm] = React.useState({
    displayName: identity._displayName || ov._displayName || base.name || clientName,
    segment: segment,
    mrr: base.mrr || "",
    health: seed("health", "green"),
    renewalDate: base.renewalDate || "",
    renewalDays: base.renewalDays || 0,
    currentProject: base.currentProject || "",
    nextCall: base.nextCall || "",
    services: (base.services || []).join(", "),
    opportunity: base.opportunity || "",
    // Champion / POC — pulled from shared identity if set, else mock seed.
    champName:  champSeed.name  || "",
    champRole:  champSeed.role  || "",
    champEmail: champSeed.email || "",
    champPhone: champSeed.phone || "",
    champRel:   champSeed.relationship || "warm",
    champNote:  champSeed.note  || "",
    // Logo — shared identity wins.
    logoMode:    seed("_logoMode",   "glyph"),
    logoLetter:  seed("_logoLetter", (clientName[0] || "·").toUpperCase()),
    logoBg:      seed("_logoBg",     currentLogo.bg),
    logoDomain:  seed("_logoDomain", clientName.toLowerCase().includes(".") ? clientName.toLowerCase() : clientName.toLowerCase().replace(/[^a-z0-9]/g,"") + ".com"),
    // Per-segment assignment from the vendors registry / free-text
    assignedMD: ov.assignedMD || "",          // for MD segment, picked from doctors list
    medicalEmployee: ov.medicalEmployee || "", // for Mgmt segment, free text
  });
  const vendors = window.useVendors ? window.useVendors() : null;
  const set = (k,v) => setForm(f => ({...f, [k]:v}));

  React.useEffect(()=>{
    const onKey = (e) => { if(e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return ()=>window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const save = () => {
    // Shared identity — same for monday.com whether viewed under MD or Mgmt.
    const champion = {
      ...(base.champion || {}),
      name: form.champName,
      role: form.champRole,
      email: form.champEmail,
      phone: form.champPhone,
      relationship: form.champRel,
      note: form.champNote,
    };
    if (window.Store && window.Store.setCompanyIdentity) {
      window.Store.setCompanyIdentity(clientName, {
        _displayName: form.displayName !== clientName ? form.displayName : undefined,
        _logoMode:    form.logoMode,
        _logoLetter:  form.logoLetter,
        _logoBg:      form.logoBg,
        _logoDomain:  form.logoDomain,
        health:       form.health,
        champion,
        poc: { name: form.champName, role: form.champRole, email: form.champEmail },
      });
    }
    // Per-engagement (segment-specific) data.
    const patch = {
      assignedMD: form.assignedMD,
      medicalEmployee: form.medicalEmployee,
      mrr: form.mrr,
      renewalDate: form.renewalDate,
      renewalDays: parseInt(form.renewalDays) || 0,
      currentProject: form.currentProject,
      nextCall: form.nextCall,
      services: form.services.split(",").map(s=>s.trim()).filter(Boolean),
      opportunity: form.opportunity,
    };
    window.Store.setCompanyOverride(clientName, segment, patch);

    // If displayName changed, also rename matching gantt lane
    if(form.displayName !== clientName){
      window.Store.setLanes(lanes => lanes.map(l =>
        l.name === clientName && (l.segment === segment) ? { ...l, name: form.displayName } : l
      ));
    }

    onClose();
  };

  return (
    <React.Fragment>
      <div className="modal-scrim on" onClick={onClose}/>
      <div className="modal edit-modal on">
        <div className="edit-modal-head">
          <div className="edit-modal-preview" style={{ background: form.logoBg }}>
            {form.logoMode === "letter" && (
              <span style={{
                fontFamily:"'Fraunces',serif", fontWeight:500,
                fontSize:30, color:"#fff", letterSpacing:"-.03em"
              }}>{(form.logoLetter || "·").toUpperCase().slice(0,2)}</span>
            )}
            {form.logoMode === "url" && (
              <CompanyGlyph name={clientName} size={44} override={{ _logoMode:"url", _logoDomain: form.logoDomain }}/>
            )}
            {form.logoMode === "glyph" && (
              <CompanyGlyph name={clientName} size={32} override={{ _logoMode: form.logoMode, _logoLetter: form.logoLetter, _logoBg: form.logoBg }}/>
            )}
          </div>
          <div className="edit-modal-titles">
            <span className="eyebrow">Edit company</span>
            <h3>{form.displayName || clientName}</h3>
          </div>
          <button className="bar-modal-close" onClick={onClose}><Icon.Close/></button>
        </div>

        <div className="edit-modal-body">
          <section className="edit-group">
            <h5>Identity</h5>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Display name</label>
                <input value={form.displayName} onChange={e=>set("displayName", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Health</label>
                <div className="bf-status-pick">
                  {HEALTH_OPTIONS.map(h => (
                    <button key={h.k}
                            className={"bf-status-chip " + (form.health===h.k?"on":"")}
                            onClick={()=>set("health", h.k)}>
                      <span className={"health-dot " + h.k} style={{margin:0}}/>
                      {h.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </section>

          <section className="edit-group">
            <h5>{segment === "mgmt" ? "Medical employee assigned" : "Assigned private MD"}</h5>
            {segment === "mgmt" ? (
              <div className="bf-field">
                <label>Employee name</label>
                <input value={form.medicalEmployee}
                       placeholder="e.g. Maya Cohen, RN"
                       onChange={e=>set("medicalEmployee", e.target.value)}/>
                <div style={{marginTop:6, fontSize:11, color:"var(--ink-muted)"}}>
                  Free text — the medical employee on this account.
                </div>
              </div>
            ) : (
              <div className="bf-field">
                <label>Doctor</label>
                {vendors && vendors.activeMedicine && vendors.activeMedicine.length > 0 ? (
                  <select value={form.assignedMD}
                          onChange={e=>set("assignedMD", e.target.value)}
                          style={{width:"100%", padding:"8px 10px", borderRadius:8, border:"1px solid var(--line)", background:"var(--bg-card)"}}>
                    <option value="">— Pick a doctor —</option>
                    {vendors.activeMedicine.map(v => (
                      <option key={v.id} value={v.name}>
                        {v.name}{v.subcategory ? " · " + v.subcategory : ""}
                      </option>
                    ))}
                  </select>
                ) : (
                  <input value={form.assignedMD}
                         placeholder="Loading doctors list…"
                         onChange={e=>set("assignedMD", e.target.value)}/>
                )}
                <div style={{marginTop:6, fontSize:11, color:"var(--ink-muted)"}}>
                  Pulled live from Medical Vendors Registry · {vendors ? (vendors.activeMedicine || []).length + " active" : "loading"}
                </div>
              </div>
            )}
          </section>

          <section className="edit-group">
            <h5>Logo</h5>
            <div className="bf-field">
              <label>Mark style</label>
              <div className="bf-status-pick">
                <button className={"bf-status-chip " + (form.logoMode==="url"?"on":"")} onClick={()=>set("logoMode","url")}>
                  Brand logo (from website)
                </button>
                <button className={"bf-status-chip " + (form.logoMode==="glyph"?"on":"")} onClick={()=>set("logoMode","glyph")}>
                  Abstract glyph
                </button>
                <button className={"bf-status-chip " + (form.logoMode==="letter"?"on":"")} onClick={()=>set("logoMode","letter")}>
                  Letter monogram
                </button>
              </div>
            </div>
            {form.logoMode === "url" && (
              <div className="bf-field">
                <label>Domain <span style={{color:"var(--ink-muted)",fontWeight:400,fontSize:11}}>· e.g. monday.com, wix.com</span></label>
                <input value={form.logoDomain}
                       placeholder="company.com"
                       onChange={e=>set("logoDomain", e.target.value)}/>
                <div style={{marginTop:6, fontSize:11, color:"var(--ink-muted)"}}>
                  Logo is fetched live from logo.clearbit.com — falls back to favicon if not found.
                </div>
              </div>
            )}
            {form.logoMode === "letter" && (
              <div className="bf-field">
                <label>Letter (1–2 chars)</label>
                <input value={form.logoLetter} maxLength={2}
                       onChange={e=>set("logoLetter", e.target.value)}/>
              </div>
            )}
            {form.logoMode !== "url" && (
              <div className="bf-field">
                <label>Color</label>
                <div className="logo-swatches">
                  {LOGO_PRESETS.map((bg, i) => (
                    <button key={i}
                            className={"logo-swatch " + (form.logoBg === bg ? "on":"")}
                            style={{ background: bg }}
                            onClick={()=>set("logoBg", bg)}/>
                  ))}
                </div>
              </div>
            )}
          </section>

          <section className="edit-group">
            <h5>Commercial</h5>
            <div className="bf-row two">
              <div className="bf-field">
                <label>MRR</label>
                <input value={form.mrr} placeholder="₪48K" onChange={e=>set("mrr", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Renewal date</label>
                <input value={form.renewalDate} placeholder="e.g. Jul 12, 2026" onChange={e=>set("renewalDate", e.target.value)}/>
              </div>
            </div>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Days until renewal</label>
                <input type="number" value={form.renewalDays} onChange={e=>set("renewalDays", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Next call</label>
                <input value={form.nextCall} onChange={e=>set("nextCall", e.target.value)}/>
              </div>
            </div>
            <div className="bf-field">
              <label>Services (comma-separated)</label>
              <input value={form.services} onChange={e=>set("services", e.target.value)}/>
            </div>
            <div className="bf-field">
              <label>Current project</label>
              <textarea rows={2} value={form.currentProject} onChange={e=>set("currentProject", e.target.value)}/>
            </div>
            <div className="bf-field">
              <label>Expansion opportunity</label>
              <textarea rows={2} value={form.opportunity} onChange={e=>set("opportunity", e.target.value)}/>
            </div>
          </section>

          <section className="edit-group">
            <h5>Champion / Primary contact</h5>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Name</label>
                <input value={form.champName} onChange={e=>set("champName", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Role</label>
                <input value={form.champRole} onChange={e=>set("champRole", e.target.value)}/>
              </div>
            </div>
            <div className="bf-row two">
              <div className="bf-field">
                <label>Email</label>
                <input value={form.champEmail} onChange={e=>set("champEmail", e.target.value)}/>
              </div>
              <div className="bf-field">
                <label>Phone</label>
                <input value={form.champPhone} onChange={e=>set("champPhone", e.target.value)}/>
              </div>
            </div>
            <div className="bf-field">
              <label>Relationship</label>
              <div className="bf-status-pick">
                {RELATIONSHIP_OPTIONS.map(r => (
                  <button key={r}
                          className={"bf-status-chip " + (form.champRel===r?"on":"")}
                          onClick={()=>set("champRel", r)}>
                    {r}
                  </button>
                ))}
              </div>
            </div>
            <div className="bf-field">
              <label>Notes about this person</label>
              <textarea rows={3} value={form.champNote} onChange={e=>set("champNote", e.target.value)}/>
            </div>
          </section>
        </div>

        <div className="bar-modal-foot">
          <div className="bar-modal-foot-right">
            <button className="btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn-primary" onClick={save}>Save changes</button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

// Live mirror of the Operations Roadmap board for a single company.
// Read = via useRoadmap (poll). Write = open the Gantt's bar editor via the
// window function GanttCalendar exposes; saves there flow back via the API.
function RoadmapEventsPanel({ companyName }) {
  const hook = window.useRoadmap ? window.useRoadmap() : null;
  const roadmap = hook ? hook.data : null;

  const lane = roadmap
    ? roadmap.lanes.find(l => (l.name || "").toLowerCase() === (companyName || "").toLowerCase())
    : null;

  const today = new Date(); today.setHours(0,0,0,0);
  const origin = new Date(today); origin.setDate(today.getDate() - 10);
  const fmtBarDate = (b) => {
    if (b._ghost) return "Unscheduled";
    const d = new Date(origin); d.setDate(d.getDate() + b.start);
    const startStr = d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) +
                     " · " + d.toLocaleDateString(undefined, { weekday: "short" });
    if (b.len > 1) {
      const e = new Date(d); e.setDate(e.getDate() + b.len - 1);
      return startStr + " → " + e.toLocaleDateString(undefined, { month: "short", day: "numeric" });
    }
    return startStr;
  };

  const openEditor = (barId) => {
    if (!lane || !window.openBarEditorByLane) return;
    window.openBarEditorByLane(lane.name, barId);
  };

  return (
    <div className="dr-section">
      <h4>
        Roadmap events
        <span style={{color:"var(--ink-muted)", fontWeight:400, marginLeft:6, fontSize:12}}>
          {lane ? `· ${lane.bars.length} on Monday board` : "· Live from Monday"}
        </span>
      </h4>
      {!roadmap && (
        <div style={{color:"var(--ink-muted)", fontSize:13, padding:"8px 0"}}>Loading…</div>
      )}
      {roadmap && !lane && (
        <div style={{color:"var(--ink-muted)", fontSize:13, padding:"8px 0", lineHeight:1.5}}>
          No matching lane on the Operations Roadmap board for <b style={{color:"var(--ink)"}}>{companyName}</b>.
          To connect, add a label "{companyName}" to the Company column on the board and create an item.
        </div>
      )}
      {lane && (
        <div style={{display:"flex", flexDirection:"column", gap:6}}>
          {lane.bars.length === 0 ? (
            <div style={{color:"var(--ink-muted)", fontSize:13}}>No events scheduled yet.</div>
          ) : (
            lane.bars.slice().sort((a, b) => (a.start ?? 1e9) - (b.start ?? 1e9)).map(b => (
              <div key={b.id}
                   onClick={() => openEditor(b.id)}
                   style={{
                     display:"flex", alignItems:"center", gap:10,
                     padding:"10px 12px", borderRadius:10,
                     background:"var(--bg-card)", border:"1px solid var(--line)",
                     cursor:"pointer",
                   }}
                   onMouseEnter={e=>{ e.currentTarget.style.borderColor="var(--accent)"; }}
                   onMouseLeave={e=>{ e.currentTarget.style.borderColor="var(--line)"; }}>
                <span style={{width:8, height:24, borderRadius:2, background: b.color, flexShrink:0}}/>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontWeight:500, color:"var(--ink)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{b.title}</div>
                  <div style={{fontSize:11, color:"var(--ink-muted)", fontFamily:"'JetBrains Mono',monospace", marginTop:2}}>
                    {fmtBarDate(b)} · {b.status}
                  </div>
                </div>
                <span style={{fontSize:11, color:"var(--ink-muted)"}}>Edit ›</span>
              </div>
            ))
          )}
          <button onClick={() => openEditor("NEW")}
                  style={{
                    display:"flex", alignItems:"center", gap:6,
                    padding:"8px 12px", borderRadius:10,
                    background:"transparent",
                    border:"1px dashed var(--line)",
                    color:"var(--ink-soft)", fontSize:13,
                    cursor:"pointer", justifyContent:"center",
                    marginTop:4,
                  }}>
            <Icon.Plus/> Add event
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ClientDrawer, EditCompanyModal });
