/* Calendar, Tasks, Content, Knowledge, Automation, Admin */

const { useState: useStateMisc } = React;

/* ─────────────────────────── Calendar ─────────────────────────── */
function PageCalendar({ onNavigate }) {
  const week = ["2026-05-18", "2026-05-19", "2026-05-20", "2026-05-21", "2026-05-22", "2026-05-23", "2026-05-24"];
  const hours = Array.from({ length: 11 }).map((_, i) => 8 + i); /* 8 → 18 */
  const [events, setEvents] = useStateMisc(window.CALENDAR_EVENTS);
  const [active, setActive] = useStateMisc(null);
  const [newOpen, setNewOpen] = useStateMisc(false);
  const [newSlot, setNewSlot] = useStateMisc(null); /* { day, start } */
  const [dragId, setDragId] = useStateMisc(null);
  const [dropTarget, setDropTarget] = useStateMisc(null); /* { day, hour } */
  const [resizing, setResizing] = useStateMisc(null); /* { id, edge, startY, origStart, origEnd } */
  const resizingRef = React.useRef(null);

  const openNew = (slot) => { setNewSlot(slot || null); setNewOpen(true); };

  /* Resize an event by dragging its top or bottom border. Snaps to 15-min increments. */
  React.useEffect(() => {
    if (!resizing) return;
    const SNAP = 15; /* minutes */
    const MIN_DUR = 15;
    const CAL_START = 8 * 60;
    const CAL_END   = 19 * 60;
    const toMin = (s) => { const [h, m] = s.split(":").map(Number); return h * 60 + m; };
    const toStr = (mins) => `${String(Math.floor(mins / 60)).padStart(2, "0")}:${String(mins % 60).padStart(2, "0")}`;

    const onMove = (e) => {
      const dy = e.clientY - resizing.startY;
      const dMin = Math.round(dy / SNAP) * SNAP; /* 60px per hour → 1px = 1min */
      setEvents(prev => prev.map(ev => {
        if (ev.id !== resizing.id) return ev;
        let startMin = toMin(resizing.origStart);
        let endMin   = toMin(resizing.origEnd);
        if (resizing.edge === "top") {
          startMin = Math.max(CAL_START, Math.min(startMin + dMin, endMin - MIN_DUR));
        } else {
          endMin = Math.min(CAL_END, Math.max(endMin + dMin, startMin + MIN_DUR));
        }
        return { ...ev, start: toStr(startMin), end: toStr(endMin) };
      }));
    };
    const onUp = () => {
      const wasResizing = !!resizingRef.current;
      resizingRef.current = null;
      setResizing(null);
      if (wasResizing) {
        /* suppress the synthetic click that follows mouseup on the underlying cell */
        const swallow = (e) => { e.stopPropagation(); e.preventDefault(); };
        document.addEventListener("click", swallow, { capture: true, once: true });
      }
    };
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
    return () => {
      document.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseup", onUp);
    };
  }, [resizing]);

  /* Move event to a new {day, hour} slot, preserving duration. */
  const rescheduleEvent = (evId, day, hour) => {
    setEvents(prev => prev.map(e => {
      if (e.id !== evId) return e;
      const [sh, sm] = e.start.split(":").map(Number);
      const [eh, em] = e.end.split(":").map(Number);
      const durMin = (eh * 60 + em) - (sh * 60 + sm);
      const newStart = `${String(hour).padStart(2, "0")}:00`;
      const endTotal = hour * 60 + durMin;
      const newEnd = `${String(Math.floor(endTotal / 60)).padStart(2, "0")}:${String(endTotal % 60).padStart(2, "0")}`;
      return { ...e, day, start: newStart, end: newEnd };
    }));
  };

  return (
    <>
      <PageHeader
        title="Calendar"
        actions={<>
          <Button kind="ghost" size="md" icon="chevron-left" />
          <Button kind="ghost" size="md">Today</Button>
          <Button kind="ghost" size="md" icon="chevron-right" />
          <Button kind="secondary" size="md" icon="filter">Week</Button>
          <Button kind="primary" size="md" icon="plus" onClick={() => openNew(null)}>New event</Button>
        </>}
      />
      <div style={{ borderTop: "1px solid var(--line)" }}>
        <div className="scroll-x" style={{ display: "grid", gridTemplateColumns: "60px repeat(7, minmax(120px, 1fr))", background: "var(--surface)" }}>
            <div style={{ background: "var(--surface-2)", borderBottom: "1px solid var(--line)" }} />
            {week.map(d => {
              const date = new Date(d);
              const isToday = d === "2026-05-22";
              return (
                <div key={d} style={{
                  padding: "10px 12px", borderBottom: "1px solid var(--line)",
                  background: isToday ? "var(--accent-soft)" : "var(--surface-2)",
                  borderLeft: "1px solid var(--line)",
                }}>
                  <div style={{ fontSize: 10.5, color: isToday ? "var(--accent-ink)" : "var(--ink-3)", fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase" }}>
                    {date.toLocaleDateString("en-GB", { weekday: "short" })}
                  </div>
                  <div className="mono num" style={{ fontSize: 16, fontWeight: 600, color: isToday ? "var(--accent-ink)" : "var(--ink)" }}>
                    {date.getDate()}
                  </div>
                </div>
              );
            })}
            {hours.map(h => (
              <React.Fragment key={h}>
                <div style={{
                  padding: "4px 8px", textAlign: "right",
                  fontSize: 11, color: "var(--ink-4)",
                  borderBottom: "1px solid var(--line)",
                  height: 60,
                }} className="mono">{String(h).padStart(2, "0")}:00</div>
                {week.map(d => {
                  const evs = events.filter(e => e.day === d && parseInt(e.start) === h);
                  const isTarget = dropTarget && dropTarget.day === d && dropTarget.hour === h;
                  /* Duration of the currently-dragged event, in minutes — drives the dashed preview height. */
                  const draggedEv = dragId ? events.find(e => e.id === dragId) : null;
                  let draggedDurMin = 60;
                  if (draggedEv) {
                    const [dsh, dsm] = draggedEv.start.split(":").map(Number);
                    const [deh, dem] = draggedEv.end.split(":").map(Number);
                    draggedDurMin = (deh * 60 + dem) - (dsh * 60 + dsm);
                  }
                  /* Don't render the preview past 19:00 — cap to remaining minutes in the day. */
                  const calEndMin = 19 * 60;
                  const previewMin = Math.min(draggedDurMin, calEndMin - h * 60);
                  const previewEndH = Math.floor((h * 60 + previewMin) / 60);
                  const previewEndM = (h * 60 + previewMin) % 60;
                  const previewEndStr = `${String(previewEndH).padStart(2, "0")}:${String(previewEndM).padStart(2, "0")}`;
                  return (
                    <div key={d}
                      onClick={(e) => {
                        if (e.target.closest("button")) return;
                        openNew({ day: d, start: `${String(h).padStart(2, "0")}:00` });
                      }}
                      onDragOver={(e) => {
                        if (!dragId) return;
                        e.preventDefault();
                        if (!isTarget) setDropTarget({ day: d, hour: h });
                      }}
                      onDragLeave={() => { if (isTarget) setDropTarget(null); }}
                      onDrop={(e) => {
                        e.preventDefault();
                        if (dragId) {
                          rescheduleEvent(dragId, d, h);
                          setDragId(null); setDropTarget(null);
                        }
                      }}
                      style={{
                        borderLeft: "1px solid var(--line)",
                        borderBottom: "1px solid var(--line)",
                        height: 60, position: "relative", padding: 3,
                        cursor: "pointer",
                        /* Elevate the active drop target so its (possibly overflowing) duration preview
                           paints above neighbouring cells, instead of being clipped behind them. */
                        zIndex: isTarget && dragId ? 20 : 1,
                        /* When something is being dragged over this cell, the dashed preview below renders the
                           outline at the exact event duration. Otherwise (hover only) fall back to a light tint. */
                        background: isTarget && !dragId ? "color-mix(in oklch, var(--accent) 14%, transparent)" : "transparent",
                        transition: "background 120ms",
                      }}
                      onMouseEnter={(e) => { if (!isTarget) e.currentTarget.style.background = "color-mix(in oklch, var(--accent) 4%, transparent)"; }}
                      onMouseLeave={(e) => { if (!isTarget) e.currentTarget.style.background = "transparent"; }}
                    >
                      {/* Drop preview — sized to the dragged meeting's duration, so the user can see
                          exactly where (and how long) it will land. */}
                      {isTarget && dragId && (
                        <div style={{
                          position: "absolute", left: 3, right: 3, top: 3,
                          height: Math.max(20, previewMin - 6),
                          borderRadius: 6,
                          background: "color-mix(in oklch, var(--accent) 14%, transparent)",
                          outline: "1.5px dashed var(--accent)",
                          outlineOffset: -1,
                          pointerEvents: "none",
                          zIndex: 5,
                          display: "flex", flexDirection: "column", justifyContent: "space-between",
                          padding: "4px 6px",
                          overflow: "hidden",
                        }}>
                          <div className="mono" style={{
                            fontSize: 10.5, fontWeight: 600, color: "var(--accent-ink)",
                            letterSpacing: "0.02em",
                          }}>
                            {String(h).padStart(2, "0")}:00 – {previewEndStr}
                          </div>
                          {previewMin >= 45 && (
                            <div className="mono" style={{
                              fontSize: 10, color: "var(--accent-ink)", opacity: 0.75,
                            }}>
                              {previewMin} min
                            </div>
                          )}
                        </div>
                      )}
                      {evs.map(ev => {
                        const startMin = parseInt(ev.start.split(":")[1]);
                        const endH = parseInt(ev.end.split(":")[0]);
                        const endM = parseInt(ev.end.split(":")[1]);
                        const durMin = (endH * 60 + endM) - (h * 60 + startMin);
                        const company = getCompany(ev.companyId);
                        const tone = ev.type === "account_review" ? "violet" : ev.type === "internal" ? "neutral" : "blue";
                        const colors = { violet: { bg: "var(--accent-soft)", bd: "var(--accent)", fg: "var(--accent-ink)" }, blue: { bg: "var(--blue-soft)", bd: "var(--blue)", fg: "var(--blue-ink)" }, neutral: { bg: "var(--inset)", bd: "var(--ink-4)", fg: "var(--ink-2)" } };
                        const c = colors[tone];
                        const isResizingThis = resizing && resizing.id === ev.id;
                        const beginResize = (edge) => (e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          const r = { id: ev.id, edge, startY: e.clientY, origStart: ev.start, origEnd: ev.end };
                          resizingRef.current = r;
                          setResizing(r);
                        };
                        return (
                          <button key={ev.id}
                            draggable={!isResizingThis}
                            onDragStart={(e) => {
                              if (resizingRef.current) { e.preventDefault(); return; }
                              setDragId(ev.id);
                              e.dataTransfer.effectAllowed = "move";
                              /* render a transparent drag image so the original stays visible */
                              const img = new Image();
                              img.src = "data:image/svg+xml;charset=utf-8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'/>";
                              try { e.dataTransfer.setDragImage(img, 0, 0); } catch (_) {}
                            }}
                            onDragEnd={() => { setDragId(null); setDropTarget(null); }}
                            onClick={(e) => { if (!dragId && !resizingRef.current) setActive(ev); }}
                            style={{
                              position: "absolute", left: 3, right: 3,
                              top: (startMin / 60) * 60 + 3,
                              height: (durMin / 60) * 60 - 6,
                              background: c.bg, border: `1px solid ${c.bd}`,
                              borderLeft: `3px solid ${c.bd}`,
                              borderRadius: 5, padding: "4px 6px",
                              textAlign: "left", overflow: "hidden",
                              cursor: isResizingThis ? "ns-resize" : (dragId === ev.id ? "grabbing" : "grab"),
                              opacity: dragId === ev.id ? 0.45 : 1,
                              transition: isResizingThis ? "none" : "transform 120ms, box-shadow 120ms, opacity 120ms",
                              zIndex: (dragId === ev.id || isResizingThis) ? 10 : 1,
                              boxShadow: isResizingThis ? "var(--shadow-2)" : "none",
                            }}
                            onMouseEnter={(e) => { if (dragId !== ev.id && !isResizingThis) { e.currentTarget.style.transform = "translateY(-1px)"; e.currentTarget.style.boxShadow = "var(--shadow-2)"; e.currentTarget.querySelectorAll("[data-resize-handle]").forEach(h => h.style.opacity = "1"); } }}
                            onMouseLeave={(e) => { if (!isResizingThis) { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = "none"; e.currentTarget.querySelectorAll("[data-resize-handle]").forEach(h => h.style.opacity = "0"); } }}
                          >
                            {/* top resize handle */}
                            <div
                              data-resize-handle="top"
                              draggable={false}
                              onMouseDown={beginResize("top")}
                              onDragStart={(e) => e.preventDefault()}
                              onClick={(e) => e.stopPropagation()}
                              title="Drag to change start time"
                              style={{
                                position: "absolute", top: -2, left: 0, right: 0, height: 7,
                                cursor: "ns-resize", zIndex: 3,
                                display: "flex", justifyContent: "center", alignItems: "flex-start",
                                opacity: isResizingThis && resizing.edge === "top" ? 1 : 0,
                                transition: "opacity 120ms",
                              }}
                            >
                              <div style={{ marginTop: 2, width: 22, height: 3, borderRadius: 2, background: c.bd }} />
                            </div>
                            <div style={{ fontSize: 11.5, fontWeight: 600, color: c.fg, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                              {ev.title}
                            </div>
                            <div style={{ fontSize: 10, color: c.fg, opacity: 0.8 }} className="mono">
                              {ev.start}–{ev.end}{company ? ` · ${company.name}` : ""}
                            </div>
                            {/* bottom resize handle */}
                            <div
                              data-resize-handle="bottom"
                              draggable={false}
                              onMouseDown={beginResize("bottom")}
                              onDragStart={(e) => e.preventDefault()}
                              onClick={(e) => e.stopPropagation()}
                              title="Drag to change end time"
                              style={{
                                position: "absolute", bottom: -2, left: 0, right: 0, height: 7,
                                cursor: "ns-resize", zIndex: 3,
                                display: "flex", justifyContent: "center", alignItems: "flex-end",
                                opacity: isResizingThis && resizing.edge === "bottom" ? 1 : 0,
                                transition: "opacity 120ms",
                              }}
                            >
                              <div style={{ marginBottom: 2, width: 22, height: 3, borderRadius: 2, background: c.bd }} />
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
      </div>

      <EventDetailModal ev={active} onClose={() => setActive(null)} onOpenAccount={(id) => { setActive(null); onNavigate("account-detail", { companyId: id }); }} />
      <NewEventModal
        open={newOpen}
        slot={newSlot}
        onClose={() => { setNewOpen(false); setNewSlot(null); }}
        onCreate={(ev) => {
          setEvents(prev => [...prev, ev]);
          setNewOpen(false);
          setNewSlot(null);
        }}
      />
    </>
  );
}

function NewEventModal({ open, slot, onClose, onCreate }) {
  const [title, setTitle]       = useStateMisc("");
  const [day, setDay]           = useStateMisc("2026-05-22");
  const [start, setStart]       = useStateMisc("10:00");
  const [duration, setDuration] = useStateMisc(30); /* minutes */
  const [type, setType]         = useStateMisc("meeting");
  const [location, setLocation] = useStateMisc("Google Meet");
  const [companyId, setCompanyId] = useStateMisc("");
  const [attendees, setAttendees] = useStateMisc([CURRENT_USER.id]);
  const [desc, setDesc]         = useStateMisc("");

  React.useEffect(() => {
    if (!open) return;
    setTitle("");
    setDay(slot?.day || "2026-05-22");
    setStart(slot?.start || "10:00");
    setDuration(30);
    setType("meeting");
    setLocation("Google Meet");
    setCompanyId("");
    setAttendees([CURRENT_USER.id]);
    setDesc("");
  }, [open, slot]);

  const computeEnd = (s, mins) => {
    const [h, m] = s.split(":").map(Number);
    const total = h * 60 + m + mins;
    return `${String(Math.floor(total / 60)).padStart(2, "0")}:${String(total % 60).padStart(2, "0")}`;
  };

  const handle = () => {
    if (!title.trim()) return;
    onCreate({
      id: "ev-" + Math.random().toString(36).slice(2, 8),
      title,
      type,
      day,
      start,
      end: computeEnd(start, duration),
      location,
      companyId: companyId || null,
      attendees,
      description: desc,
    });
  };

  const toggleAttendee = (id) => {
    setAttendees(prev => prev.includes(id) ? prev.filter(a => a !== id) : [...prev, id]);
  };

  const TYPES = [
    { id: "meeting",        label: "External meeting", tone: "blue",   icon: "users" },
    { id: "account_review", label: "Account review",   tone: "violet", icon: "target" },
    { id: "internal",       label: "Internal",         tone: "neutral", icon: "users-2" },
  ];

  /* candidate attendees: users + recent contacts */
  const userOpts = window.USERS;
  const contactOpts = window.CONTACTS.slice(0, 6);

  return (
    <window.Modal
      open={open} onClose={onClose}
      icon="calendar"
      title="New event"
      subtitle="Schedules in your connected calendar and pings attendees."
      width={560}
      footer={<>
        <Button kind="ghost" onClick={onClose}>Cancel</Button>
        <Button kind="primary" icon="plus" onClick={handle} disabled={!title.trim()}>Create event</Button>
      </>}
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <window.FormField label="Title" span={2}>
          <window.FormInput
            autoFocus value={title} onChange={(e) => setTitle(e.target.value)}
            placeholder="e.g. Pricing walkthrough with Mango"
          />
        </window.FormField>

        <window.FormField label="Type" span={2}>
          <div style={{ display: "flex", gap: 6 }}>
            {TYPES.map(t => {
              const selected = type === t.id;
              const c = ({ violet: "var(--accent)", blue: "var(--blue)", neutral: "var(--ink-3)" })[t.tone];
              return (
                <button key={t.id} onClick={() => setType(t.id)} style={{
                  flex: 1, padding: "9px 10px", borderRadius: 7,
                  border: `1px solid ${selected ? c : "var(--line-strong)"}`,
                  background: selected ? `color-mix(in oklch, ${c} 10%, transparent)` : "var(--surface)",
                  color: selected ? "var(--ink)" : "var(--ink-2)",
                  display: "flex", alignItems: "center", gap: 7,
                  fontSize: 12.5, fontWeight: selected ? 600 : 500,
                  transition: "background 120ms, border-color 120ms",
                  cursor: "pointer",
                }}>
                  <Icon name={t.icon} size={13} style={{ color: c }} />
                  {t.label}
                </button>
              );
            })}
          </div>
        </window.FormField>

        <window.FormField label="Date">
          <window.FormInput type="date" value={day} onChange={(e) => setDay(e.target.value)} />
        </window.FormField>
        <window.FormField label="Start">
          <window.FormInput type="time" value={start} onChange={(e) => setStart(e.target.value)} />
        </window.FormField>

        <window.FormField label="Duration" span={2}>
          <div style={{ display: "flex", gap: 4 }}>
            {[15, 30, 45, 60, 90].map(m => (
              <button key={m} onClick={() => setDuration(m)} style={{
                flex: 1, padding: "6px 8px", borderRadius: 6,
                border: `1px solid ${duration === m ? "var(--ink)" : "var(--line-strong)"}`,
                background: duration === m ? "var(--inset)" : "var(--surface)",
                color: "var(--ink)",
                fontSize: 12, fontWeight: duration === m ? 600 : 500,
                cursor: "pointer",
              }}>{m === 60 ? "1 h" : m === 90 ? "1.5 h" : `${m} min`}</button>
            ))}
            <span style={{ alignSelf: "center", fontSize: 11.5, color: "var(--ink-3)" }} className="mono">
              ends {computeEnd(start, duration)}
            </span>
          </div>
        </window.FormField>

        <window.FormField label="Location">
          <window.FormSelect value={location} onChange={(e) => setLocation(e.target.value)} options={[
            { value: "Google Meet", label: "Google Meet" },
            { value: "Zoom", label: "Zoom" },
            { value: "Microsoft Teams", label: "Microsoft Teams" },
            { value: "Phone", label: "Phone call" },
            { value: "Onsite", label: "Onsite" },
            { value: "Internal", label: "Internal" },
          ]} />
        </window.FormField>
        <window.FormField label="Account" optional>
          <window.FormSelect value={companyId} onChange={(e) => setCompanyId(e.target.value)}
            options={[{ value: "", label: "—" }, ...window.COMPANIES.map(c => ({ value: c.id, label: c.name }))]} />
        </window.FormField>

        <window.FormField label="Attendees" span={2}>
          <div style={{
            display: "flex", flexWrap: "wrap", gap: 5,
            padding: 6,
            background: "var(--surface-2)",
            border: "1px solid var(--line)", borderRadius: 8,
          }}>
            {[...userOpts, ...contactOpts.filter(c => companyId ? c.companyId === companyId : true)].map(p => {
              const id = p.id;
              const name = p.name || `${p.firstName} ${p.lastName}`;
              const src  = p.profilePictureUrl;
              const isUser = !!p.email && !p.headline;
              const selected = attendees.includes(id);
              return (
                <button key={id} onClick={() => toggleAttendee(id)} style={{
                  display: "inline-flex", alignItems: "center", gap: 6,
                  padding: "3px 8px 3px 3px",
                  borderRadius: 999,
                  background: selected ? "var(--accent-soft)" : "var(--surface)",
                  border: `1px solid ${selected ? "color-mix(in oklch, var(--accent) 30%, transparent)" : "var(--line-strong)"}`,
                  color: selected ? "var(--accent-ink)" : "var(--ink-2)",
                  fontSize: 12,
                  cursor: "pointer",
                  transition: "background 120ms, border-color 120ms",
                }}>
                  <Avatar name={name} src={src} size={18} />
                  <span>{name}</span>
                  {!isUser && <span style={{ fontSize: 10, color: "var(--ink-4)" }}>· ext.</span>}
                </button>
              );
            })}
          </div>
        </window.FormField>

        <window.FormField label="Notes" span={2} optional>
          <window.FormTextarea
            value={desc} onChange={(e) => setDesc(e.target.value)}
            placeholder="Agenda, context, links…"
          />
        </window.FormField>
      </div>

      <div style={{
        marginTop: 14, padding: 10,
        background: "var(--accent-soft)",
        border: "1px solid color-mix(in oklch, var(--accent) 18%, transparent)",
        borderRadius: 7,
        fontSize: 12, color: "var(--accent-ink)",
        display: "flex", alignItems: "center", gap: 8,
      }}>
        <Icon name="sparkles" size={12} />
        <span>AI will prep talking points and a draft agenda 30 min before the event.</span>
      </div>
    </window.Modal>
  );
}

function EventDetailModal({ ev, onClose, onOpenAccount }) {
  if (!ev) return null;
  const company = getCompany(ev.companyId);
  const attendees = (ev.attendees || []).map(id => getUser(id) || (window.CONTACTS.find(c => c.id === id) && {
    id, name: `${window.CONTACTS.find(c => c.id === id).firstName} ${window.CONTACTS.find(c => c.id === id).lastName}`,
    src: window.CONTACTS.find(c => c.id === id).profilePictureUrl,
  })).filter(Boolean);
  return (
    <window.Modal open={!!ev} onClose={onClose}
      icon="calendar" title={ev.title}
      subtitle={`${fmtDate(ev.day, { weekday: "long", day: "2-digit", month: "long" })} · ${ev.start}–${ev.end}`}
      footer={<>
        <Button kind="ghost" onClick={onClose}>Close</Button>
        {company && <Button kind="secondary" icon="external" onClick={() => onOpenAccount(company.id)}>Open account</Button>}
        <Button kind="primary" icon="check" onClick={onClose}>Confirm RSVP</Button>
      </>}>
      <div style={{ display: "grid", rowGap: 14 }}>
        <DetailRow k="Location" v={<span><Icon name="map-pin" size={11} style={{ verticalAlign: "middle", marginRight: 4, color: "var(--ink-4)" }} />{ev.location}</span>} />
        {company && <DetailRow k="Account"  v={<span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><CompanyLogo company={company} size={20} />{company.name}</span>} />}
        <DetailRow k="Attendees" v={<div style={{ display: "flex", gap: -4 }}>
          {attendees.map((a, i) => <div key={a.id} style={{ marginLeft: i > 0 ? -6 : 0 }}><Avatar name={a.name} src={a.src} size={24} title={a.name} /></div>)}
        </div>} />
        <DetailRow k="Type" v={<Badge tone={ev.type === "account_review" ? "violet" : ev.type === "internal" ? "neutral" : "blue"}>{ev.type.replace(/_/g, " ")}</Badge>} />
      </div>
      <div style={{ marginTop: 16, padding: 12, borderRadius: 8, background: "var(--accent-soft)", border: "1px solid color-mix(in oklch, var(--accent) 18%, transparent)", fontSize: 12.5, color: "var(--accent-ink)", display: "flex", alignItems: "flex-start", gap: 8 }}>
        <Icon name="sparkles" size={13} style={{ marginTop: 2, flexShrink: 0 }} />
        <span>AI prep: 3 talking points + draft agenda ready 30 minutes before start.</span>
      </div>
    </window.Modal>
  );
}

function DetailRow({ k, v }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 12, alignItems: "center", fontSize: 13 }}>
      <dt style={{ color: "var(--ink-3)" }}>{k}</dt>
      <dd style={{ margin: 0, color: "var(--ink)", fontWeight: 500 }}>{v}</dd>
    </div>
  );
}

/* ─────────────────────────── Tasks ─────────────────────────── */
function PageTasks() {
  const [tasks, setTasks] = useStateMisc(window.TASKS);
  const [filter, setFilter] = useStateMisc("open");
  const [newOpen, setNewOpen] = useStateMisc(false);
  const [editing, setEditing] = useStateMisc(null);

  const filtered = tasks.filter(t => {
    if (filter === "open")   return t.status !== "done" && t.status !== "cancelled";
    if (filter === "done")   return t.status === "done";
    if (filter === "mine")   return t.assignedUserId === CURRENT_USER.id;
    return true;
  });

  const toggle = (id) => setTasks(prev => prev.map(t => {
    if (t.id !== id) return t;
    return { ...t, status: t.status === "done" ? "todo" : "done" };
  }));

  const saveEdits = (patch) => setTasks(prev => prev.map(t => t.id === editing.id ? { ...t, ...patch } : t));
  const deleteTask = () => { setTasks(prev => prev.filter(t => t.id !== editing.id)); setEditing(null); };

  return (
    <>
      <PageHeader
        title="Tasks"
        actions={<>
          <Button kind="secondary" size="md" icon="filter">Filter</Button>
          <Button kind="primary" size="md" icon="plus" onClick={() => setNewOpen(true)}>New task</Button>
        </>}
        tabs={<>
          <Tab active={filter === "open"} onClick={() => setFilter("open")} badge={tasks.filter(t => t.status !== "done").length}>Open</Tab>
          <Tab active={filter === "mine"} onClick={() => setFilter("mine")} badge={tasks.filter(t => t.assignedUserId === CURRENT_USER.id).length}>Mine</Tab>
          <Tab active={filter === "done"} onClick={() => setFilter("done")} badge={tasks.filter(t => t.status === "done").length}>Done</Tab>
          <Tab active={filter === "all"} onClick={() => setFilter("all")}>All</Tab>
        </>}
      />
      <div className="page-pad page-pad-y">
        <TasksList tasks={filtered} onToggle={toggle} onEdit={setEditing} />
      </div>

      <TaskModal
        open={newOpen}
        onClose={() => setNewOpen(false)}
        onSubmit={(t) => { setTasks(prev => [t, ...prev]); setNewOpen(false); }}
      />
      <TaskModal
        open={!!editing}
        editing={editing}
        onClose={() => setEditing(null)}
        onSubmit={(patch) => { saveEdits(patch); setEditing(null); }}
        onDelete={deleteTask}
      />
    </>
  );
}

function TaskModal({ open, onClose, onSubmit, onDelete, editing }) {
  const isEdit = !!editing;
  const [title, setTitle] = useStateMisc("");
  const [description, setDescription] = useStateMisc("");
  const [priority, setPriority] = useStateMisc("medium");
  const [companyIds, setCompanyIds] = useStateMisc([]);
  const [contactIds, setContactIds] = useStateMisc([]);
  const [ownerId, setOwnerId] = useStateMisc(CURRENT_USER.id);
  const [status, setStatus] = useStateMisc("todo");
  const [due, setDue] = useStateMisc("2026-05-25");
  const [confirmDel, setConfirmDel] = useStateMisc(false);

  React.useEffect(() => {
    if (!open) return;
    if (isEdit) {
      setTitle(editing.title || "");
      setDescription(editing.description || "");
      setPriority(editing.priority || "medium");
      /* Read either the new arrays or the legacy single id */
      setCompanyIds(editing.companyIds || (editing.companyId ? [editing.companyId] : []));
      setContactIds(editing.contactIds || (editing.contactId ? [editing.contactId] : []));
      setOwnerId(editing.assignedUserId || CURRENT_USER.id);
      setStatus(editing.status || "todo");
      setDue((editing.dueAt || "2026-05-25T09:00:00.000Z").slice(0, 10));
    } else {
      setTitle(""); setDescription(""); setPriority("medium");
      setCompanyIds([]); setContactIds([]);
      setOwnerId(CURRENT_USER.id);
      setStatus("todo"); setDue("2026-05-25");
    }
    setConfirmDel(false);
  }, [open, isEdit, editing]);

  const handle = () => {
    if (!title.trim()) return;
    const payload = {
      title, description, priority,
      companyIds, contactIds,
      /* Keep legacy single-id fields populated with the first selection
         so existing UI that reads task.companyId / task.contactId keeps
         working transparently. */
      companyId: companyIds[0] || null,
      contactId: contactIds[0] || null,
      assignedUserId: ownerId, status,
      dueAt: due + "T09:00:00.000Z",
    };
    if (isEdit) {
      onSubmit(payload);
    } else {
      onSubmit({
        id: "task-" + Math.random().toString(36).slice(2, 8),
        opportunityId: null,
        createdAt: new Date().toISOString(),
        ...payload,
      });
    }
  };

  /* Contacts list filtered to selected companies (or all if no company picked) */
  const contactPool = window.CONTACTS.filter(c => companyIds.length === 0 || companyIds.includes(c.companyId));

  return (
    <window.Modal
      open={open} onClose={onClose}
      icon="check-square"
      title={isEdit ? "Edit task" : "New task"}
      subtitle={isEdit ? `Last updated · ${fmtRelative(editing?.dueAt)}` : undefined}
      width={560}
      footer={
        isEdit ? (
          confirmDel ? (
            <>
              <span style={{ fontSize: 12, color: "var(--ink-3)", marginRight: "auto" }}>Delete this task?</span>
              <Button kind="ghost" onClick={() => setConfirmDel(false)}>Cancel</Button>
              <Button kind="danger" icon="trash" onClick={onDelete}>Delete</Button>
            </>
          ) : (
            <>
              <Button kind="ghost" icon="trash" onClick={() => setConfirmDel(true)} style={{ marginRight: "auto", color: "var(--red-ink)" }}>Delete</Button>
              <Button kind="ghost" onClick={onClose}>Cancel</Button>
              <Button kind="primary" icon="check" onClick={handle} disabled={!title.trim()}>Save changes</Button>
            </>
          )
        ) : (
          <>
            <Button kind="ghost" onClick={onClose}>Cancel</Button>
            <Button kind="primary" icon="plus" onClick={handle} disabled={!title.trim()}>Create task</Button>
          </>
        )
      }
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <window.FormField label="Title" span={2}>
          <window.FormInput autoFocus value={title} onChange={(e) => setTitle(e.target.value)} placeholder="What needs to happen?" />
        </window.FormField>
        <window.FormField label="Description" span={2} optional>
          <window.FormTextarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Add context, links or instructions…" />
        </window.FormField>

        {/* Owner — single user */}
        <window.FormField label="Owner">
          <UserPicker value={ownerId} onChange={setOwnerId} />
        </window.FormField>
        <window.FormField label="Priority">
          <window.FormSelect value={priority} onChange={(e) => setPriority(e.target.value)}
            options={[
              { value: "high", label: "High" }, { value: "medium", label: "Medium" }, { value: "low", label: "Low" },
            ]} />
        </window.FormField>

        {/* Accounts — multi */}
        <window.FormField label="Accounts" span={2} optional>
          <MultiTagPicker
            kind="account"
            ids={companyIds}
            onChange={(ids) => {
              setCompanyIds(ids);
              /* Drop any selected contact that no longer matches the company filter */
              setContactIds(prev => prev.filter(cid => {
                const c = window.CONTACTS.find(x => x.id === cid);
                return !c || ids.length === 0 || ids.includes(c.companyId);
              }));
            }}
            options={window.COMPANIES}
            getKey={(c) => c.id}
            getLabel={(c) => c.name}
            getSubLabel={(c) => c.industry}
            renderAvatar={(c) => <CompanyLogo company={c} size={18} />}
            placeholder="Add an account…"
          />
        </window.FormField>

        {/* Contacts — multi (filtered by selected companies) */}
        <window.FormField label="Contacts" span={2} optional>
          <MultiTagPicker
            kind="contact"
            ids={contactIds}
            onChange={setContactIds}
            options={contactPool}
            getKey={(c) => c.id}
            getLabel={(c) => `${c.firstName} ${c.lastName}`}
            getSubLabel={(c) => `${c.position}${c.companyName ? " · " + c.companyName : ""}`}
            renderAvatar={(c) => <Avatar name={`${c.firstName} ${c.lastName}`} src={c.profilePictureUrl} size={18} />}
            placeholder={companyIds.length ? "Add a contact at the selected account(s)…" : "Add a contact…"}
            emptyHint={companyIds.length && contactPool.length === 0 ? "No contacts at the selected account(s)." : null}
          />
        </window.FormField>

        <window.FormField label="Status">
          <window.FormSelect value={status} onChange={(e) => setStatus(e.target.value)}
            options={[
              { value: "todo", label: "To do" },
              { value: "in_progress", label: "In progress" },
              { value: "blocked", label: "Blocked" },
              { value: "done", label: "Done" },
              { value: "cancelled", label: "Cancelled" },
            ]} />
        </window.FormField>
        <window.FormField label="Due date">
          <window.FormInput type="date" value={due} onChange={(e) => setDue(e.target.value)} />
        </window.FormField>
      </div>
    </window.Modal>
  );
}

/* Owner picker — single user, button + popover with avatars */
function UserPicker({ value, onChange }) {
  const [open, setOpen] = useStateMisc(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, [open]);
  const current = window.USERS.find(u => u.id === value);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: "flex", alignItems: "center", gap: 8,
        width: "100%", padding: "6px 10px",
        background: "var(--surface)",
        border: `1px solid ${open ? "var(--accent)" : "var(--line-strong)"}`,
        boxShadow: open ? "0 0 0 3px color-mix(in oklch, var(--accent) 18%, transparent)" : "none",
        borderRadius: 7,
        cursor: "pointer", textAlign: "left",
        fontSize: 13,
      }}>
        <Avatar name={current?.name} size={20} />
        <span style={{ flex: 1, color: "var(--ink)", fontWeight: 500 }}>{current?.name || "—"}</span>
        <Icon name="chevron-down" size={11} style={{ color: "var(--ink-4)" }} />
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0,
          minWidth: 220, zIndex: 60,
          background: "var(--surface)",
          border: "1px solid var(--line-strong)",
          borderRadius: 8,
          boxShadow: "0 16px 40px oklch(0.2 0 0 / 0.14), 0 2px 6px oklch(0.2 0 0 / 0.06)",
          padding: 4, animation: "fadein 140ms ease",
        }}>
          {window.USERS.map(u => (
            <button key={u.id} onClick={() => { onChange(u.id); setOpen(false); }}
              style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "6px 8px", width: "100%", textAlign: "left", borderRadius: 5,
                fontSize: 13,
                background: u.id === value ? "var(--inset)" : "transparent",
                color: "var(--ink)",
              }}
              onMouseEnter={(e) => { if (u.id !== value) e.currentTarget.style.background = "var(--surface-2)"; }}
              onMouseLeave={(e) => { if (u.id !== value) e.currentTarget.style.background = "transparent"; }}
            >
              <Avatar name={u.name} size={20} />
              <span style={{ flex: 1 }}>{u.name}</span>
              {u.id === value && <Icon name="check" size={11} stroke={2.4} />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* Generic multi-tag picker — selected items render as chips with × buttons,
   adding a chip opens a search popover. */
function MultiTagPicker({ ids, onChange, options, getKey, getLabel, getSubLabel, renderAvatar, placeholder, emptyHint }) {
  const [open, setOpen] = useStateMisc(false);
  const [q, setQ] = useStateMisc("");
  const ref = React.useRef(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => { if (!ref.current?.contains(e.target)) { setOpen(false); setQ(""); } };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, [open]);

  const selected = ids.map(id => options.find(o => getKey(o) === id)).filter(Boolean);
  const filtered = options.filter(o => {
    if (ids.includes(getKey(o))) return false;
    if (!q) return true;
    return (getLabel(o) + " " + (getSubLabel(o) || "")).toLowerCase().includes(q.toLowerCase());
  }).slice(0, 8);

  const remove = (id) => onChange(ids.filter(x => x !== id));
  const add = (id) => { onChange([...ids, id]); setQ(""); inputRef.current?.focus(); };

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <div
        onClick={() => { setOpen(true); inputRef.current?.focus(); }}
        style={{
          display: "flex", flexWrap: "wrap", gap: 4,
          padding: 5, minHeight: 36,
          background: "var(--surface)",
          border: `1px solid ${open ? "var(--accent)" : "var(--line-strong)"}`,
          boxShadow: open ? "0 0 0 3px color-mix(in oklch, var(--accent) 18%, transparent)" : "none",
          borderRadius: 7, cursor: "text",
          alignItems: "center",
        }}
      >
        {selected.map(o => (
          <span key={getKey(o)} style={{
            display: "inline-flex", alignItems: "center", gap: 5,
            padding: "2px 4px 2px 4px", borderRadius: 999,
            background: "var(--inset)",
            border: "1px solid var(--line-strong)",
            fontSize: 12, color: "var(--ink-2)", fontWeight: 500,
            maxWidth: "100%",
          }}>
            {renderAvatar?.(o)}
            <span style={{ paddingLeft: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 220 }}>{getLabel(o)}</span>
            <button onClick={(e) => { e.stopPropagation(); remove(getKey(o)); }} title="Remove" style={{
              width: 16, height: 16, borderRadius: "50%",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              color: "var(--ink-3)",
              background: "transparent",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--red-soft)"; e.currentTarget.style.color = "var(--red-ink)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-3)"; }}
            >
              <Icon name="x" size={10} stroke={2.4} />
            </button>
          </span>
        ))}
        <input
          ref={inputRef}
          value={q}
          onChange={(e) => { setQ(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)}
          placeholder={selected.length === 0 ? placeholder : ""}
          style={{
            flex: 1, minWidth: 120,
            padding: "4px 6px",
            border: "none", outline: "none", background: "transparent",
            fontSize: 13, color: "var(--ink)",
          }}
          onKeyDown={(e) => {
            if (e.key === "Backspace" && !q && selected.length > 0) {
              remove(getKey(selected[selected.length - 1]));
            } else if (e.key === "Escape") {
              setOpen(false); inputRef.current?.blur();
            } else if (e.key === "Enter" && filtered[0]) {
              e.preventDefault(); add(getKey(filtered[0]));
            }
          }}
        />
      </div>

      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0,
          maxHeight: 260, overflowY: "auto",
          background: "var(--surface)",
          border: "1px solid var(--line-strong)",
          borderRadius: 8,
          boxShadow: "0 16px 40px oklch(0.2 0 0 / 0.14), 0 2px 6px oklch(0.2 0 0 / 0.06)",
          padding: 4, zIndex: 60,
          animation: "fadein 140ms ease",
        }}>
          {emptyHint && filtered.length === 0 ? (
            <div style={{ padding: "10px 12px", fontSize: 12, color: "var(--ink-3)", fontStyle: "italic" }}>
              {emptyHint}
            </div>
          ) : filtered.length === 0 ? (
            <div style={{ padding: "10px 12px", fontSize: 12, color: "var(--ink-3)", fontStyle: "italic" }}>
              {q ? "No matches." : "All added."}
            </div>
          ) : filtered.map(o => (
            <button key={getKey(o)} onMouseDown={(e) => { e.preventDefault(); add(getKey(o)); }}
              style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "6px 8px", width: "100%", textAlign: "left", borderRadius: 5,
                fontSize: 13,
                background: "transparent",
                color: "var(--ink)",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
            >
              {renderAvatar?.(o)}
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{getLabel(o)}</div>
                {getSubLabel && getSubLabel(o) && (
                  <div style={{ fontSize: 11, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{getSubLabel(o)}</div>
                )}
              </div>
              <Icon name="plus" size={11} style={{ color: "var(--ink-4)" }} />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function TasksList({ tasks, onToggle = () => {}, onEdit }) {
  if (tasks.length === 0) return <EmptyState icon="check-square" title="No tasks" />;
  return (
    <Card padding={0} style={{ overflow: "hidden" }}>
      {tasks.map((t, i) => {
        const company = getCompany(t.companyId);
        const contact = getContact(t.contactId);
        const user    = getUser(t.assignedUserId);
        const done    = t.status === "done";
        const overdue = !done && new Date(t.dueAt) < new Date("2026-05-21T00:00:00Z");
        return (
          <div key={t.id}
            onClick={() => onEdit?.(t)}
            style={{
              display: "grid",
              gridTemplateColumns: "30px 1fr auto auto auto auto",
              padding: "14px 18px",
              gap: 14, alignItems: "center",
              borderBottom: i < tasks.length - 1 ? "1px solid var(--line)" : "none",
              background: done ? "var(--surface-2)" : "var(--surface)",
              opacity: done ? 0.65 : 1,
              cursor: onEdit ? "pointer" : "default",
              transition: "background 120ms",
            }}
            onMouseEnter={(e) => { if (onEdit) e.currentTarget.style.background = done ? "var(--inset)" : "var(--surface-2)"; }}
            onMouseLeave={(e) => { if (onEdit) e.currentTarget.style.background = done ? "var(--surface-2)" : "var(--surface)"; }}
          >
            <button onClick={(e) => { e.stopPropagation(); onToggle(t.id); }} style={{
              width: 18, height: 18, borderRadius: "50%",
              border: done ? "none" : "1.5px solid var(--line-strong)",
              background: done ? "var(--green)" : "var(--surface)",
              display: "flex", alignItems: "center", justifyContent: "center",
              color: "#fff",
            }}>
              {done && <Icon name="check" size={11} stroke={3} />}
            </button>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)", textDecoration: done ? "line-through" : "none" }}>
                {t.title}
              </div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{t.description}</div>
            </div>
            {company && <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--ink-2)" }}>
              <CompanyLogo company={company} size={20} />{company.name}
            </div>}
            {!company && <div />}
            <Badge tone={t.priority === "high" ? "warm" : t.priority === "medium" ? "blue" : "neutral"}>{t.priority}</Badge>
            <div className="mono" style={{ fontSize: 11.5, color: overdue ? "var(--red-ink)" : "var(--ink-3)", fontWeight: overdue ? 600 : 400, whiteSpace: "nowrap" }}>
              {overdue && "OVERDUE · "}{fmtDate(t.dueAt, { day: "2-digit", month: "short" })}
            </div>
            <Avatar name={user?.name} size={22} title={user?.name} />
          </div>
        );
      })}
    </Card>
  );
}

/* ─────────────────────────── Content ─────────────────────────── */
function PageContent() {
  return (
    <>
      <PageHeader
        title="Content Library"
        actions={<>
          <Button kind="secondary" size="md" icon="filter">Filter</Button>
          <Button kind="primary" size="md" icon="plus">Upload asset</Button>
        </>}
      />
      <div className="page-pad page-pad-y grid-auto-260">
        {window.CONTENT.map(c => (
          <Card key={c.id} padding={0} style={{ overflow: "hidden", display: "flex", flexDirection: "column" }}>
            <div style={{
              height: 110, position: "relative",
              background: `repeating-linear-gradient(45deg, var(--inset) 0 8px, var(--surface-2) 8px 16px)`,
              display: "flex", alignItems: "center", justifyContent: "center",
              borderBottom: "1px solid var(--line)",
            }}>
              <div style={{
                background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 6,
                padding: "6px 10px", fontSize: 11, fontWeight: 500, color: "var(--ink-2)",
                display: "flex", alignItems: "center", gap: 6,
              }}>
                <Icon name="file-text" size={12} />
                <span className="mono" style={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>{c.type.replace(/_/g, " ")}</span>
              </div>
            </div>
            <div style={{ padding: 14, display: "flex", flexDirection: "column", gap: 6, flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.35 }}>{c.title}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.45, flex: 1 }}>{c.description}</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 4 }}>
                {c.approved
                  ? <Badge tone="green" size="sm" icon="check">Approved</Badge>
                  : <Badge tone="warm" size="sm" icon="clock">Pending review</Badge>}
                <Badge tone="neutral" size="sm">{c.language.toUpperCase()}</Badge>
              </div>
              <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
                <Button size="sm">Preview</Button>
                <Button size="sm" icon="paperclip">Use in message</Button>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </>
  );
}

/* ─────────────────────────── Knowledge ─────────────────────────── */
function PageKnowledge() {
  const product = window.CONTENT && {
    differentiators: ["Company-first CRM model", "Unified contact conversation workspace", "AI next-best actions", "LinkedIn relationship intelligence"],
    pitch: [
      "Replace fragmented sales tools with one ABM operating system.",
      "Centralize every stakeholder conversation and signal.",
      "Use AI to prioritize accounts and personalize outreach.",
    ],
    objections: [
      { q: "We already use a CRM", a: "BusinessTeam complements CRM workflows with ABM execution, relationship intelligence and multi-channel workspace built around target accounts." },
      { q: "Our team already uses LinkedIn manually", a: "BusinessTeam adds structure, visibility, sync, prioritization and team coordination to LinkedIn prospecting." },
    ],
  };
  return (
    <>
      <PageHeader
        title="Product Knowledge"
        actions={<>
          <Button kind="secondary" size="md" icon="edit">Edit</Button>
          <Button kind="primary" size="md" icon="sparkles">Train copilot</Button>
        </>}
      />
      <div className="page-pad page-pad-y form-2col">
        <Card padding={20}>
          <SectionTitle>Positioning</SectionTitle>
          <p style={{ fontSize: 14, lineHeight: 1.6, margin: "8px 0 16px", color: "var(--ink-2)" }} className="serif">
            BusinessTeam helps revenue teams identify target accounts, map buying committees, engage stakeholders with AI-personalized outreach, and orchestrate multi-channel ABM execution from one collaborative workspace.
          </p>
          <SectionTitle>Differentiators</SectionTitle>
          <ul style={{ paddingLeft: 18, margin: "8px 0 0", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.7 }}>
            {product.differentiators.map((d, i) => <li key={i}>{d}</li>)}
          </ul>
        </Card>
        <Card padding={20}>
          <SectionTitle>Pitch elements</SectionTitle>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 6 }}>
            {product.pitch.map((p, i) => (
              <div key={i} style={{ padding: "10px 12px", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 8, fontSize: 13 }}>
                <span className="mono" style={{ color: "var(--ink-4)", marginRight: 8 }}>{String(i+1).padStart(2,"0")}</span>
                {p}
              </div>
            ))}
          </div>
        </Card>
        <Card padding={20} style={{ gridColumn: "1 / -1" }}>
          <SectionTitle>Objection handling</SectionTitle>
          <div className="form-2col" style={{ marginTop: 6 }}>
            {product.objections.map((o, i) => (
              <div key={i}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)", marginBottom: 4 }}>
                  <span style={{ color: "var(--warm-ink)" }}>"</span>{o.q}<span style={{ color: "var(--warm-ink)" }}>"</span>
                </div>
                <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.55 }}>
                  <span style={{ color: "var(--accent)", fontWeight: 600 }}>→</span> {o.a}
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </>
  );
}

/* ─────────────────────────── Automation ─────────────────────────── */
function PageAutomation() {
  const [dryRun, setDryRun] = useStateMisc(true);
  const [pace, setPace] = useStateMisc("careful");

  return (
    <>
      <PageHeader
        title="Outreach Automation"
        actions={<>
          <Button kind="secondary" size="md" icon="refresh">Sync invitations</Button>
          <Button kind="primary" size="md" icon="play">Start campaign</Button>
        </>}
      />
      <div className="page-pad page-pad-y dash-2col">
        {/* Campaign builder */}
        <Card padding={0}>
          <SectionHeader title="Executive LinkedIn campaign · draft"
            right={<Badge tone="warm" icon="circle-dot">Draft</Badge>} />
          <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 18 }}>

            <ConfigRow label="Target seniority"
              hint="Higher levels get prioritized routing.">
              <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
                {["Owner", "C-level", "VP", "Director", "Head"].map(s => <Badge key={s} tone="violet">{s}</Badge>)}
              </div>
            </ConfigRow>

            <ConfigRow label="Channels" hint="Currently only LinkedIn invites are supported.">
              <Badge tone="blue" icon="linkedin">LinkedIn</Badge>
            </ConfigRow>

            <ConfigRow label="Daily limit" hint="40/day is the safe range.">
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <input type="range" min="10" max="100" defaultValue="40" style={{ width: 200 }} />
                <span className="mono num" style={{ fontSize: 13, fontWeight: 600 }}>40 / day</span>
              </div>
            </ConfigRow>

            <ConfigRow label="Pacing" hint="Delay between requests randomized within range.">
              <div style={{ display: "flex", border: "1px solid var(--line-strong)", borderRadius: 6, overflow: "hidden" }}>
                {[
                  { id: "fast",     label: "Fast · 1–2 min" },
                  { id: "careful",  label: "Careful · 2–5 min" },
                  { id: "stealth",  label: "Stealth · 5–10 min" },
                ].map(p => (
                  <button key={p.id} onClick={() => setPace(p.id)} style={{
                    padding: "5px 10px", fontSize: 12, fontWeight: 500,
                    background: pace === p.id ? "var(--inset)" : "transparent",
                    color: pace === p.id ? "var(--ink)" : "var(--ink-3)",
                    borderRight: "1px solid var(--line)",
                  }}>{p.label}</button>
                ))}
              </div>
            </ConfigRow>

            <ConfigRow label="Safety rules" hint="Built-in guardrails — recommended on.">
              <div style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 12.5 }}>
                <SafetyToggle label="Skip already connected" defaultOn />
                <SafetyToggle label="Skip pending invitations" defaultOn />
                <SafetyToggle label="Skip contacts without LinkedIn ID" defaultOn />
              </div>
            </ConfigRow>

            <ConfigRow label="Dry run" hint="Preview what would be sent — no actual messages.">
              <button onClick={() => setDryRun(d => !d)} style={{
                width: 36, height: 20, borderRadius: 999,
                background: dryRun ? "var(--accent)" : "var(--line-strong)",
                padding: 2, transition: "background 200ms",
              }}>
                <div style={{
                  width: 16, height: 16, borderRadius: "50%", background: "#fff",
                  transform: dryRun ? "translateX(16px)" : "translateX(0)",
                  transition: "transform 200ms",
                  boxShadow: "0 1px 2px rgba(0,0,0,0.15)",
                }} />
              </button>
            </ConfigRow>
          </div>
        </Card>

        {/* Preview */}
        <Card padding={0}>
          <SectionHeader title="Preview · would send" right={<span className="mono num" style={{ fontSize: 12, color: "var(--ink-3)" }}>3 of 40</span>} />
          <div style={{ padding: "0 0 8px" }}>
            {window.CONTACTS.filter(c => ["c_level", "vp", "director", "head"].includes(c.seniority) && c.linkedinStatus !== "accepted").slice(0, 5).map(c => (
              <div key={c.id} style={{
                display: "grid", gridTemplateColumns: "32px 1fr 100px",
                padding: "10px 16px", gap: 10, alignItems: "center",
                borderBottom: "1px solid var(--line)",
              }}>
                <Avatar name={`${c.firstName} ${c.lastName}`} src={c.profilePictureUrl} size={28} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{c.firstName} {c.lastName}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.headline}</div>
                </div>
                <Badge tone="violet" size="sm">{SENIORITY_LABEL[c.seniority]}</Badge>
              </div>
            ))}
          </div>
          <div style={{ padding: 14, background: "var(--surface-2)", borderTop: "1px solid var(--line)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <Icon name="sparkles" size={12} style={{ color: "var(--accent)" }} />
              <span style={{ fontSize: 12, fontWeight: 600 }}>AI-personalized invite (preview)</span>
            </div>
            <div style={{ padding: 10, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 6, fontSize: 12, lineHeight: 1.5, color: "var(--ink-2)" }}>
              "Hi {"{firstName}"}, came across your work at {"{companyName}"} — I lead an ABM platform helping {"{department}"} leaders coordinate execution across stakeholders. Would love to swap notes."
            </div>
          </div>
        </Card>

        {/* Recent sync runs */}
        <Card padding={0} style={{ gridColumn: "1 / -1" }}>
          <SectionHeader title="Sync runs" right={<Button kind="ghost" size="sm" icon="refresh">Refresh</Button>} />
          {[
            { id: "sync-1", type: "LinkedIn relations sync", fetched: 823, synced: 137, status: "completed_with_warning", at: "2026-05-20T04:08Z", note: "Large response — frontend should prefer summarized sync." },
            { id: "sync-2", type: "Sent invitations sync",   fetched: 380, synced: 252, status: "completed", at: "2026-05-20T06:45Z", note: "Optimized with preload." },
            { id: "sync-3", type: "Manager+Head invite send", fetched: 0,   synced: 28,  status: "completed", at: "2026-05-19T12:30Z", note: "Dry run successful." },
          ].map(s => (
            <div key={s.id} style={{
              display: "grid", gridTemplateColumns: "30px 1fr 120px 120px 110px",
              padding: "12px 18px", gap: 14, alignItems: "center",
              borderBottom: "1px solid var(--line)",
            }}>
              <div style={{ width: 22, height: 22, borderRadius: "50%", background: s.status === "completed" ? "var(--green-soft)" : "var(--warm-soft)", color: s.status === "completed" ? "var(--green-ink)" : "var(--warm-ink)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <Icon name={s.status === "completed" ? "check" : "alert"} size={12} />
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{s.type}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{s.note}</div>
              </div>
              <div className="mono num" style={{ fontSize: 12, color: "var(--ink-2)" }}>{s.fetched} fetched</div>
              <div className="mono num" style={{ fontSize: 12, color: "var(--ink-2)" }}>{s.synced} synced</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{fmtRelative(s.at)}</div>
            </div>
          ))}
        </Card>
      </div>
    </>
  );
}

function ConfigRow({ label, hint, children }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "180px 1fr", gap: 16, alignItems: "flex-start" }}>
      <div>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{label}</div>
        {hint && <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.4 }}>{hint}</div>}
      </div>
      <div>{children}</div>
    </div>
  );
}

function SafetyToggle({ label, defaultOn }) {
  const [on, setOn] = useStateMisc(defaultOn);
  return (
    <button onClick={() => setOn(!on)} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-2)" }}>
      <span style={{
        width: 14, height: 14, borderRadius: 4,
        background: on ? "var(--green)" : "var(--surface)",
        border: on ? "none" : "1px solid var(--line-strong)",
        color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
      }}>{on && <Icon name="check" size={9} stroke={3} />}</span>
      {label}
    </button>
  );
}

/* ─────────────────────────── Admin ─────────────────────────── */
function PageAdmin() {
  const [section, setSection] = useStateMisc("organization");
  return (
    <div className="admin-shell">
      <PageHeader
        title="Administration"
      />
      <div className="admin-body">
        <div className="admin-nav" style={{ display: "flex", flexDirection: "column", gap: 1 }}>
          {[
            ["organization", "Organization", "building"],
            ["pitch",        "Company Pitch", "presentation"],
            ["icp",          "ABM setup", "target"],
            ["products",     "Products catalog", "briefcase"],
            ["team",         "Team members", "users"],
            ["ai",           "AI agents", "sparkles"],
            ["competitors",  "Competitors", "shield"],
            ["notifications","Notifications", "bell"],
          ].map(([id, label, icon]) => (
            <button key={id} onClick={() => setSection(id)} style={{
              display: "flex", alignItems: "center", gap: 8,
              padding: "8px 10px", borderRadius: 7,
              fontSize: 13, fontWeight: section === id ? 600 : 500,
              color: section === id ? "var(--ink)" : "var(--ink-2)",
              background: section === id ? "var(--surface)" : "transparent",
              boxShadow: section === id ? "var(--shadow-1)" : "none",
              border: section === id ? "1px solid var(--line)" : "1px solid transparent",
              textAlign: "left",
            }}>
              <Icon name={icon} size={14} style={{ color: section === id ? (id === "ai" ? "var(--accent)" : "var(--ink-2)") : "var(--ink-3)" }} />
              {label}
            </button>
          ))}
        </div>
        <div className="admin-pane">
          {section === "organization" && <AdminOrg />}
          {section === "pitch" && <AdminPitch />}
          {section === "icp" && <AdminICP />}
          {section === "products" && <AdminProducts />}
          {section === "team" && <AdminTeam />}
          {section === "ai" && <AdminAI />}
          {section === "competitors" && <AdminCompetitors />}
          {section === "notifications" && <AdminNotifications />}
        </div>
      </div>
    </div>
  );
}

function AdminOrg() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {/* Identity */}
      <Card padding={24}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Brand identity</h3>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>How your organization shows up across the platform and outreach.</div>

        <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 24, marginTop: 20, alignItems: "flex-start" }}>
          <LogoField />
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Field label="Organization name" value="BusinessTeam Demo Organization" />
            <Field label="Tagline" value="Turn account intelligence into coordinated execution." />
            <Field label="Description" value="An AI-powered ABM operating system that unifies relationship intelligence, omnichannel engagement and strategic orchestration in a single workspace." multiline />
            <Field label="Industry" value="B2B SaaS · Sales technology" />
          </div>
        </div>

        {/* Website + thumbnail */}
        <div style={{ marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 8 }}>Website</div>
          <WebsitePreview />
        </div>

        {/* Website + thumbnail */}
        <div style={{ marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 8 }}>Website</div>
          <WebsitePreview />
        </div>
      </Card>

      {/* Contact */}
      <Card padding={24}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Contact details</h3>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>Used in email signatures and outbound footers.</div>

        <ContactEmailsBlock />

        <div style={{ marginTop: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 8 }}>Headquarters</div>
          <AddressList />
        </div>
      </Card>

      {/* Web & social */}
      <Card padding={24}>
        <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 8 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Web &amp; social</h3>
          <span style={{ flex: 1 }} />
          <Button kind="ghost" size="sm" icon="plus">Add channel</Button>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>Where prospects can find you. Verified accounts boost outreach response rates.</div>

        <div style={{
          marginTop: 20,
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 260px), 1fr))",
          gap: 14,
        }}>
          <SocialField icon="globe"   label="Website"   value="https://businessteam.example" verified />
          <SocialField icon="linkedin" label="LinkedIn" value="linkedin.com/company/businessteam-demo" verified />
          <SocialField icon="presentation" label="YouTube" value="youtube.com/@businessteam" />
          <SocialField icon="message-circle" label="X (Twitter)" value="x.com/businessteam_" />
          <SocialField icon="image"   label="Instagram" value="instagram.com/businessteam.demo" />
          <SocialField icon="users"   label="Facebook"  value="facebook.com/businessteam.demo" />
          <SocialField icon="briefcase" label="Crunchbase" value="crunchbase.com/organization/businessteam" />
          <SocialField icon="link"    label="Other" value="" placeholder="Custom URL" />
        </div>
      </Card>

      {/* Brand colors — separate trailing block */}
      <Card padding={24}>
        <div style={{ display: "flex", alignItems: "baseline", flexWrap: "wrap", gap: 10 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Brand colors</h3>
          <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>
            Used by AI to match outreach assets and email templates.
          </span>
        </div>
        <div style={{ marginTop: 20 }}>
          <BrandColorTheme />
        </div>
      </Card>
    </div>
  );
}

/* Contact emails block — phone (single) + dynamic list of emails with a
   per-row role label + "Add email" text button. */
function ContactEmailsBlock() {
  const [phone, setPhone] = useStateMisc("+34 932 000 100");
  const [emails, setEmails] = useStateMisc([
    { id: "e1", label: "General", value: "hello@businessteam.example" },
    { id: "e2", label: "Support", value: "support@businessteam.example" },
    { id: "e3", label: "Billing", value: "billing@businessteam.example" },
  ]);

  const ROLE_OPTIONS = ["General", "Support", "Billing", "Sales", "Press", "Privacy", "Careers", "Partnerships", "Other"];
  const update = (id, key, val) => setEmails(prev => prev.map(e => e.id === id ? { ...e, [key]: val } : e));
  const remove = (id) => setEmails(prev => prev.filter(e => e.id !== id));
  const addEmail = () => {
    const used = new Set(emails.map(e => e.label));
    const nextLabel = ROLE_OPTIONS.find(r => !used.has(r)) || "Other";
    setEmails(prev => [...prev, { id: "e-" + Math.random().toString(36).slice(2, 6), label: nextLabel, value: "" }]);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 20 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Field label="General phone" icon="phone" value={phone} onChange={setPhone} />
      </div>

      <div>
        <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 8, display: "flex", alignItems: "center", gap: 6 }}>
          <Icon name="mail" size={11} />
          Emails
          <span className="mono num" style={{ color: "var(--ink-4)", fontWeight: 500 }}>{emails.length}</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {emails.map(em => (
            <div key={em.id} style={{
              display: "grid",
              gridTemplateColumns: "minmax(120px, 0.8fr) 1fr 28px",
              gap: 8, alignItems: "stretch",
            }}>
              <select
                value={em.label}
                onChange={(e) => update(em.id, "label", e.target.value)}
                style={{
                  padding: "8px 10px", fontSize: 13, fontWeight: 500,
                  background: "var(--surface-2)",
                  border: "1px solid var(--line-strong)", borderRadius: 7,
                  color: "var(--ink-2)", outline: "none",
                  appearance: "none",
                  backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round'><path d='M6 9l6 6 6-6'/></svg>\")",
                  backgroundRepeat: "no-repeat",
                  backgroundPosition: "right 8px center",
                  paddingRight: 26,
                }}
              >
                {ROLE_OPTIONS.map(r => <option key={r} value={r}>{r}</option>)}
              </select>
              <input
                value={em.value}
                onChange={(e) => update(em.id, "value", e.target.value)}
                placeholder="name@company.com"
                style={{
                  padding: "8px 10px", fontSize: 13,
                  background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 7,
                  color: "var(--ink)", outline: "none",
                }}
              />
              <button
                onClick={() => remove(em.id)}
                title="Remove email"
                disabled={emails.length === 1}
                style={{
                  width: 28, borderRadius: 6,
                  color: "var(--ink-3)",
                  background: "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  opacity: emails.length === 1 ? 0.3 : 1,
                  cursor: emails.length === 1 ? "not-allowed" : "pointer",
                  transition: "background 120ms, color 120ms",
                }}
                onMouseEnter={(e) => { if (emails.length > 1) { e.currentTarget.style.background = "var(--red-soft)"; e.currentTarget.style.color = "var(--red-ink)"; } }}
                onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-3)"; }}
              >
                <Icon name="trash" size={12} />
              </button>
            </div>
          ))}
          <button onClick={addEmail} style={{
            alignSelf: "flex-start",
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "6px 10px", marginTop: 2, borderRadius: 6,
            fontSize: 12.5, fontWeight: 500,
            color: "var(--accent-ink)",
            background: "transparent", border: "1px dashed transparent",
            transition: "background 120ms, border-color 120ms",
          }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--accent-soft)"; e.currentTarget.style.borderColor = "color-mix(in oklch, var(--accent) 22%, transparent)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent";       e.currentTarget.style.borderColor = "transparent"; }}
          >
            <Icon name="plus" size={12} />
            Add email
          </button>
        </div>
      </div>
    </div>
  );
}

/* Address list — primary HQ + optional additional offices + "Add location" CTA */
function AddressList() {
  const [addrs, setAddrs] = useStateMisc([
    { id: "hq", label: "Headquarters", street: "Carrer de la Diputació, 246", city: "Barcelona", postal: "08007", country: "Spain", primary: true },
  ]);

  const addLocation = () => {
    const id = "addr-" + Math.random().toString(36).slice(2, 6);
    setAddrs(prev => [...prev, { id, label: "Office", street: "", city: "", postal: "", country: "", primary: false }]);
  };
  const update = (id, key, val) => setAddrs(prev => prev.map(a => a.id === id ? { ...a, [key]: val } : a));
  const remove = (id) => setAddrs(prev => prev.filter(a => a.id !== id));
  const setPrimary = (id) => setAddrs(prev => prev.map(a => ({ ...a, primary: a.id === id })));

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {addrs.map(a => (
        <div key={a.id} style={{
          border: "1px solid var(--line)", borderRadius: 8,
          padding: 12, background: "var(--surface)",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <Icon name="map-pin" size={12} style={{ color: "var(--ink-3)" }} />
            <input
              value={a.label}
              onChange={(e) => update(a.id, "label", e.target.value)}
              placeholder="Label (e.g. NYC office)"
              style={{
                flex: 1, padding: "4px 6px", fontSize: 12.5, fontWeight: 600,
                background: "transparent", border: "1px solid transparent", borderRadius: 5,
                color: "var(--ink)", outline: "none",
              }}
              onFocus={(e) => { e.currentTarget.style.background = "var(--surface-2)"; e.currentTarget.style.borderColor = "var(--line-strong)"; }}
              onBlur={(e)  => { e.currentTarget.style.background = "transparent";       e.currentTarget.style.borderColor = "transparent"; }}
            />
            {a.primary
              ? <Badge tone="violet" size="sm" dot>Primary</Badge>
              : <button onClick={() => setPrimary(a.id)} style={{ fontSize: 11, color: "var(--ink-3)", padding: "2px 6px" }}>Set primary</button>}
            {!a.primary && <IconButton icon="trash" title="Remove location" onClick={() => remove(a.id)} />}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 12 }}>
            <Field label="Street"      value={a.street}  compact onChange={(v) => update(a.id, "street", v)} />
            <Field label="City"        value={a.city}    compact onChange={(v) => update(a.id, "city", v)} />
            <Field label="Postal code" value={a.postal}  compact onChange={(v) => update(a.id, "postal", v)} />
            <Field label="Country"     value={a.country} compact onChange={(v) => update(a.id, "country", v)} />
          </div>
        </div>
      ))}
      <button onClick={addLocation} style={{
        alignSelf: "flex-start",
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "6px 10px", borderRadius: 6,
        fontSize: 12.5, fontWeight: 500,
        color: "var(--accent-ink)",
        background: "transparent", border: "1px dashed transparent",
        transition: "background 120ms, border-color 120ms",
      }}
        onMouseEnter={(e) => { e.currentTarget.style.background = "var(--accent-soft)"; e.currentTarget.style.borderColor = "color-mix(in oklch, var(--accent) 22%, transparent)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = "transparent";       e.currentTarget.style.borderColor = "transparent"; }}
      >
        <Icon name="plus" size={12} />
        Add location
      </button>
    </div>
  );
}

/* Website preview — URL field on the left, screenshot-style thumbnail card on the right */
function WebsitePreview() {
  const [url, setUrl] = useStateMisc("https://businessteam.example");
  const [thumbUrl, setThumbUrl] = useStateMisc(null);
  const fileRef = React.useRef(null);

  const onFile = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => setThumbUrl(reader.result);
    reader.readAsDataURL(f);
    e.target.value = "";
  };

  const cleanHost = url.replace(/^https?:\/\//, "").replace(/\/$/, "");

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 220px", gap: 16, alignItems: "flex-start" }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <div style={{
          display: "flex", alignItems: "center",
          background: "var(--surface)",
          border: "1px solid var(--line-strong)",
          borderRadius: 7, overflow: "hidden",
        }}>
          <span style={{ padding: "8px 10px", color: "var(--ink-3)", background: "var(--surface-2)", borderRight: "1px solid var(--line)", display: "flex", alignItems: "center" }}>
            <Icon name="globe" size={14} />
          </span>
          <input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://your-site.com"
            style={{ flex: 1, padding: "8px 10px", fontSize: 13, background: "transparent", border: "none", outline: "none", color: "var(--ink)" }} />
          <button onClick={() => window.open(url, "_blank")} title="Open" style={{ padding: "0 10px", color: "var(--ink-3)" }}>
            <Icon name="external" size={13} />
          </button>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <Button kind="secondary" size="sm" icon="refresh" onClick={() => { setThumbUrl(null); /* simulate refetch by clearing */ }}>
            Refetch preview
          </Button>
          <Button kind="ghost" size="sm" icon="image" onClick={() => fileRef.current?.click()}>
            Upload custom
          </Button>
          {thumbUrl && <Button kind="ghost" size="sm" icon="trash" onClick={() => setThumbUrl(null)}>Reset</Button>}
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-4)" }}>
          Preview is auto-fetched from your site's OG image and used in shared links.
        </div>
        <input ref={fileRef} type="file" accept="image/*" style={{ display: "none" }} onChange={onFile} />
      </div>

      {/* Thumbnail card */}
      <div style={{
        width: 220, borderRadius: 10, overflow: "hidden",
        border: "1px solid var(--line)",
        background: "var(--surface-2)",
        boxShadow: "var(--shadow-1)",
        cursor: "pointer",
      }}
        onClick={() => fileRef.current?.click()}
        title="Click to replace preview image"
      >
        <div style={{
          height: 120, position: "relative", overflow: "hidden",
          background: thumbUrl ? "#000" : "linear-gradient(135deg, var(--accent) 0%, oklch(0.42 0.18 262) 100%)",
        }}>
          {thumbUrl ? (
            <img src={thumbUrl} alt="Website preview" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          ) : (
            /* Synthetic preview: mock browser frame + B mark */
            <>
              <div style={{
                position: "absolute", inset: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: "#fff", fontWeight: 700, fontSize: 32, letterSpacing: "-0.02em",
                textShadow: "0 2px 8px rgba(0,0,0,0.25)",
              }}>
                <span style={{ fontFamily: "var(--font-serif)", fontWeight: 400, fontSize: 36, fontStyle: "italic" }}>
                  Business<span style={{ opacity: 0.55 }}>Team</span>
                </span>
              </div>
              <div style={{ position: "absolute", left: 12, bottom: 10, display: "flex", gap: 4 }}>
                {[0, 1, 2].map(i => <span key={i} style={{ width: 18, height: 4, borderRadius: 3, background: "rgba(255,255,255,0.6)" }} />)}
              </div>
            </>
          )}
        </div>
        <div style={{ padding: "8px 10px", fontSize: 11.5 }}>
          <div className="mono" style={{ color: "var(--ink-2)", fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {cleanHost}
          </div>
          <div style={{ color: "var(--ink-4)", fontSize: 10.5, marginTop: 1 }}>
            {thumbUrl ? "Custom upload" : "Auto-fetched OG image"}
          </div>
        </div>
      </div>
    </div>
  );
}

/* Brand color theme — primary / secondary / tertiary swatches with picker. */
function BrandColorTheme() {
  const PALETTES = [
    { id: "indigo",  name: "Indigo Pulse",  colors: ["#5B5BD6", "#0E1530", "#F2F0EA"] },
    { id: "violet",  name: "Violet Studio", colors: ["#7C3AED", "#1E1330", "#F6F4FA"] },
    { id: "ember",   name: "Ember Suite",   colors: ["#E36F36", "#2A1A12", "#F8F0E8"] },
    { id: "jade",    name: "Jade Office",   colors: ["#1FA37A", "#0E2A20", "#EEF6F0"] },
    { id: "graphite",name: "Graphite",      colors: ["#1F2937", "#6B7280", "#F4F4F5"] },
  ];

  const [primary,   setPrimary]   = useStateMisc("#5B5BD6");
  const [secondary, setSecondary] = useStateMisc("#0E1530");
  const [tertiary,  setTertiary]  = useStateMisc("#F2F0EA");
  const [openPicker, setOpenPicker] = useStateMisc(null); /* "primary" | "secondary" | "tertiary" | null */

  const applyPalette = (p) => { setPrimary(p.colors[0]); setSecondary(p.colors[1]); setTertiary(p.colors[2]); };
  const matchingPaletteId = PALETTES.find(p =>
    p.colors[0].toLowerCase() === primary.toLowerCase() &&
    p.colors[1].toLowerCase() === secondary.toLowerCase() &&
    p.colors[2].toLowerCase() === tertiary.toLowerCase()
  )?.id;

  return (
    <div>
      {/* Three swatch fields */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
        <SwatchField label="Primary"   value={primary}   onChange={setPrimary}   open={openPicker === "primary"}   onToggle={() => setOpenPicker(openPicker === "primary"   ? null : "primary")} />
        <SwatchField label="Secondary" value={secondary} onChange={setSecondary} open={openPicker === "secondary"} onToggle={() => setOpenPicker(openPicker === "secondary" ? null : "secondary")} />
        <SwatchField label="Tertiary"  value={tertiary}  onChange={setTertiary}  open={openPicker === "tertiary"}  onToggle={() => setOpenPicker(openPicker === "tertiary"  ? null : "tertiary")} />
      </div>

      {/* Live preview pill */}
      <div style={{ marginTop: 14, padding: 14, borderRadius: 10, background: tertiary, border: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8, background: primary,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: "#fff", fontWeight: 700, fontSize: 18,
          boxShadow: "inset 0 1px 0 rgba(255,255,255,0.18)",
        }}>B</div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: secondary }}>BusinessTeam</div>
          <div style={{ fontSize: 11.5, color: secondary, opacity: 0.7 }}>Sample of how your colors appear on a card</div>
        </div>
        <button style={{
          padding: "6px 12px", borderRadius: 7,
          background: primary, color: "#fff",
          fontSize: 12, fontWeight: 600,
          boxShadow: "inset 0 1px 0 rgba(255,255,255,0.12)",
        }}>Primary CTA</button>
        <button style={{
          padding: "6px 12px", borderRadius: 7,
          background: "transparent", color: secondary,
          border: `1px solid ${secondary}`,
          fontSize: 12, fontWeight: 600,
        }}>Secondary</button>
      </div>

      {/* Presets */}
      <div style={{ marginTop: 16 }}>
        <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Or pick a preset</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          {PALETTES.map(p => {
            const active = matchingPaletteId === p.id;
            return (
              <button key={p.id} onClick={() => applyPalette(p)} style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "6px 8px 6px 6px", borderRadius: 8,
                border: `1px solid ${active ? "var(--ink)" : "var(--line)"}`,
                background: active ? "var(--inset)" : "var(--surface)",
                cursor: "pointer", transition: "background 120ms, border-color 120ms",
              }}>
                <span style={{ display: "inline-flex", borderRadius: 5, overflow: "hidden", border: "1px solid rgba(0,0,0,0.06)" }}>
                  {p.colors.map((c, i) => <span key={i} style={{ width: 14, height: 18, background: c }} />)}
                </span>
                <span style={{ fontSize: 12, fontWeight: 500, color: "var(--ink-2)" }}>{p.name}</span>
                {active && <Icon name="check" size={11} stroke={2.4} style={{ color: "var(--ink)" }} />}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function SwatchField({ label, value, onChange, open, onToggle }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => { if (!ref.current?.contains(e.target)) onToggle(); };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, [open, onToggle]);

  const QUICK = ["#5B5BD6", "#7C3AED", "#E36F36", "#1FA37A", "#0EA5E9", "#EF4444", "#0E1530", "#1F2937", "#6B7280", "#F2F0EA", "#F6F4FA", "#FFFFFF"];

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 5 }}>{label}</div>
      <button onClick={onToggle} style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: 6, width: "100%",
        background: "var(--surface)",
        border: `1px solid ${open ? "var(--accent)" : "var(--line-strong)"}`,
        boxShadow: open ? "0 0 0 3px color-mix(in oklch, var(--accent) 18%, transparent)" : "none",
        borderRadius: 8,
        transition: "border-color 120ms, box-shadow 120ms",
        cursor: "pointer",
      }}>
        <span style={{
          width: 32, height: 32, borderRadius: 6,
          background: value,
          boxShadow: "inset 0 0 0 1px rgba(0,0,0,0.08)",
          flexShrink: 0,
        }} />
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", flex: 1, minWidth: 0 }}>
          <span className="mono" style={{ fontSize: 12, color: "var(--ink)", fontWeight: 500 }}>{value.toUpperCase()}</span>
          <span style={{ fontSize: 10.5, color: "var(--ink-3)" }}>Click to edit</span>
        </div>
        <Icon name="chevron-down" size={11} style={{ color: "var(--ink-4)" }} />
      </button>

      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0,
          minWidth: 240, zIndex: 80,
          background: "var(--surface)",
          border: "1px solid var(--line-strong)",
          borderRadius: 10,
          boxShadow: "0 16px 40px oklch(0.2 0 0 / 0.14), 0 2px 6px oklch(0.2 0 0 / 0.06)",
          padding: 10, animation: "fadein 140ms ease",
        }}>
          <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Pick a color</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 6 }}>
            {QUICK.map(c => (
              <button key={c} onClick={() => onChange(c)} title={c} style={{
                width: 28, height: 28, borderRadius: 6,
                background: c,
                border: c.toLowerCase() === value.toLowerCase() ? "2px solid var(--ink)" : "1px solid rgba(0,0,0,0.08)",
                cursor: "pointer",
              }} />
            ))}
          </div>
          <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 6 }}>
            <input type="color" value={value} onChange={(e) => onChange(e.target.value)}
              style={{ width: 28, height: 28, border: "1px solid var(--line-strong)", borderRadius: 6, padding: 0, cursor: "pointer", background: "transparent" }} />
            <input value={value} onChange={(e) => onChange(e.target.value)}
              className="mono"
              style={{ flex: 1, padding: "6px 8px", fontSize: 12, background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 6, color: "var(--ink)", outline: "none" }} />
          </div>
        </div>
      )}
    </div>
  );
}

/* Logo uploader — square dropzone with current logo preview */
function LogoField() {
  const [logoUrl, setLogoUrl] = useStateMisc(null);
  const fileRef = React.useRef(null);

  const handleFile = (file) => {
    if (!file) return;
    if (!file.type.startsWith("image/")) return;
    const reader = new FileReader();
    reader.onload = () => setLogoUrl(reader.result);
    reader.readAsDataURL(file);
  };
  const onInputChange = (e) => { handleFile(e.target.files?.[0]); e.target.value = ""; };

  const [dragOver, setDragOver] = useStateMisc(false);

  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10, width: 124 }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", alignSelf: "stretch" }}>Logo</div>

      <div
        onClick={() => fileRef.current?.click()}
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={(e) => { e.preventDefault(); setDragOver(false); handleFile(e.dataTransfer.files?.[0]); }}
        style={{
          width: 112, height: 112,
          borderRadius: 14,
          background: logoUrl ? "var(--surface)" : "var(--ink)",
          color: "#fff", fontWeight: 700, fontSize: 40, letterSpacing: "-0.02em",
          display: "flex", alignItems: "center", justifyContent: "center",
          position: "relative", overflow: "hidden",
          boxShadow: "inset 0 1px 0 rgba(255,255,255,0.08), 0 1px 2px rgba(0,0,0,0.06)",
          border: dragOver ? "2px dashed var(--accent)" : "2px solid transparent",
          cursor: "pointer",
          transition: "border-color 120ms",
        }}
      >
        {logoUrl ? (
          <img src={logoUrl} alt="Organization logo" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        ) : (
          <>
            <div style={{
              position: "absolute", top: 0, right: 0,
              width: 24, height: 24,
              background: "var(--accent)",
              borderBottomLeftRadius: 14,
            }} />
            B
          </>
        )}

        {/* hover overlay */}
        <div
          className="logo-edit-overlay"
          style={{
            position: "absolute", inset: 0,
            display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4,
            background: "color-mix(in oklch, oklch(0.2 0 0) 55%, transparent)",
            color: "#fff",
            opacity: dragOver ? 1 : 0,
            transition: "opacity 140ms ease",
            fontSize: 11,
          }}
        >
          <Icon name="image" size={20} />
          <span style={{ fontWeight: 600 }}>{logoUrl ? "Replace" : "Drop image"}</span>
        </div>
        <style>{`
          div[role=logo-upload]:hover .logo-edit-overlay { opacity: 1; }
        `}</style>
      </div>

      <input
        ref={fileRef}
        type="file" accept="image/*"
        style={{ display: "none" }}
        onChange={onInputChange}
      />

      <div style={{ display: "flex", gap: 4 }}>
        <Button kind="secondary" size="sm" icon="image" onClick={() => fileRef.current?.click()}>
          {logoUrl ? "Replace" : "Upload"}
        </Button>
        {logoUrl && <IconButton icon="trash" title="Remove logo" onClick={() => setLogoUrl(null)} />}
      </div>
      <div style={{ fontSize: 10.5, color: "var(--ink-4)", textAlign: "center" }}>PNG or SVG · 1:1 · &lt;1 MB</div>
    </div>
  );
}

/* Social account row — icon + URL field + verified status */
function SocialField({ icon, label, value, verified, placeholder }) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 5 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", display: "flex", alignItems: "center", gap: 5 }}>
          <Icon name={icon} size={11} />
          {label}
        </div>
        {value && (
          verified
            ? <Badge tone="green" size="sm" icon="check">Verified</Badge>
            : <button style={{ fontSize: 11, color: "var(--accent-ink)", fontWeight: 600 }}>Verify</button>
        )}
      </div>
      <div style={{
        display: "flex", alignItems: "center",
        background: "var(--surface)",
        border: "1px solid var(--line-strong)",
        borderRadius: 7, overflow: "hidden",
      }}>
        <span style={{
          padding: "8px 10px",
          color: "var(--ink-3)",
          background: "var(--surface-2)",
          borderRight: "1px solid var(--line)",
          display: "flex", alignItems: "center",
        }}>
          <Icon name={icon} size={14} />
        </span>
        <input
          defaultValue={value}
          placeholder={placeholder || "Add URL"}
          style={{
            flex: 1, padding: "8px 10px", fontSize: 13,
            background: "transparent", border: "none", outline: "none",
            color: "var(--ink)",
          }}
        />
        {value && (
          <button title="Open" style={{ padding: "0 10px", color: "var(--ink-3)" }}>
            <Icon name="external" size={13} />
          </button>
        )}
      </div>
    </div>
  );
}

function AdminPitch() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Card padding={24}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Messaging framework</h3>
          <AIChip>used by copilot</AIChip>
          <span style={{ flex: 1 }} />
          <Button kind="ghost" size="sm" icon="sparkles" style={{ color: "var(--accent)" }}>Rewrite with AI</Button>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.5, maxWidth: 640 }}>
          Your AI copilot draws on these to draft outreach, summarize accounts and recommend content.
          Keep them tight and specific.
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 20 }}>
          <Field label="USP" value="AI-powered ABM operating system for high-touch B2B sales execution." multiline />
          <Field label="Primary narrative" value="Turn account intelligence into coordinated relationship-driven sales execution." multiline />
          <Field label="Strategic positioning" value="Premium CRM and sales engagement platform for ABM teams selling complex B2B solutions." multiline />
          <Field label="One-line elevator pitch" value="BusinessTeam helps revenue teams identify target accounts, map buying committees, and orchestrate multi-channel ABM execution from one collaborative workspace." multiline />
        </div>
      </Card>

      <Card padding={24}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Value pillars</h3>
          <Button kind="ghost" size="sm" icon="plus">Add pillar</Button>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {[
            "Company-centric ABM",
            "Relationship intelligence",
            "Omnichannel engagement",
            "AI-assisted execution",
            "Strategic orchestration",
          ].map(v => <PitchChip key={v} tone="violet" label={v} />)}
        </div>
      </Card>

      <Card padding={24}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Pain points we address</h3>
          <Button kind="ghost" size="sm" icon="plus">Add pain point</Button>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {[
            "Fragmented CRM data",
            "Low-context outreach",
            "Poor account coordination",
            "Manual research burden",
            "Weak signal detection",
          ].map(v => <PitchChip key={v} tone="warm" label={v} />)}
        </div>
      </Card>

      <Card padding={24}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Proof points</h3>
          <Button kind="ghost" size="sm" icon="plus">Add proof point</Button>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {[
            "Centralized stakeholder map",
            "Unified communication timeline",
            "AI next-best actions",
            "LinkedIn relationship sync",
          ].map(v => <PitchChip key={v} tone="green" label={v} />)}
        </div>
      </Card>
    </div>
  );
}

/* Editable chip — visually a Badge with an inline remove affordance */
function PitchChip({ label, tone }) {
  const [hover, setHover] = useStateMisc(false);
  return (
    <span
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ position: "relative", display: "inline-flex" }}
    >
      <Badge tone={tone} style={{ paddingRight: hover ? 24 : undefined, transition: "padding 120ms" }}>
        {label}
      </Badge>
      {hover && (
        <button
          title="Remove"
          style={{
            position: "absolute", right: 4, top: "50%", transform: "translateY(-50%)",
            width: 14, height: 14, borderRadius: "50%",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "var(--ink-2)",
          }}
        >
          <Icon name="x" size={10} stroke={2.4} />
        </button>
      )}
    </span>
  );
}

function AdminICP() {
  const useCases = [
    {
      id: "uc-hr-spain",
      name: "HR leadership in Spanish mid-market and enterprise",
      description: "HR directors, people leaders and talent leaders in Spanish companies with complex workforce needs.",
      active: true,
      target: { departments: "Human Resources", seniority: "Owner → Manager", geo: "Spain · 200+ employees" },
      scoringRules: [
        ["company.employee_count", "≥ 500", "+15"],
        ["contact.department",      "= human_resources", "+25"],
        ["contact.seniority",       "∈ [director, head, c_level]", "+30"],
        ["linkedin.status",         "= accepted", "+20"],
      ],
      personas: [
        {
          id: "p1", name: "Pilar — HR Director / VP People",
          department: "Human Resources", seniority: "Director / VP",
          description: "Senior HR leader responsible for workforce strategy, talent management and operational HR across multi-site organizations.",
          painPoints: ["Fragmented HR tools", "Manual workforce reporting", "Limited stakeholder visibility", "High admin burden"],
          interests: ["Workforce analytics", "Employee experience", "Retention strategy", "HR digital transformation"],
          keywords: ["people ops", "HR transformation", "HRIS", "talent ops"],
          solutions: ["Unified workforce timeline", "AI HR insights", "Stakeholder mapping", "Automated reporting"],
        },
        {
          id: "p2", name: "Carla — Head of Talent Acquisition",
          department: "Human Resources", seniority: "Head / Manager",
          description: "Owns the hiring funnel, employer brand and recruiter productivity in scaling organizations.",
          painPoints: ["Slow pipeline velocity", "Weak candidate signal", "Recruiter productivity", "Disjointed sourcing tools"],
          interests: ["Sourcing automation", "Employer brand", "Candidate experience", "Recruiter enablement"],
          keywords: ["TA", "recruiting", "sourcing", "employer brand"],
          solutions: ["ABM-style sourcing", "Candidate intelligence", "Automated outreach"],
        },
      ],
    },
  ];

  const [activeUC, setActiveUC] = useStateMisc(useCases[0].id);
  const uc = useCases.find(u => u.id === activeUC) || useCases[0];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Card padding={0}>
        <div style={{ padding: 18, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>ABM setup</h3>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
              Define ideal customer profiles, scoring rules, and the buyer personas your team targets within each use case.
            </div>
          </div>
          <Button kind="secondary" size="md" icon="copy">Duplicate</Button>
          <Button kind="primary" size="md" icon="plus">New use case</Button>
        </div>

        {/* Use-case tabs */}
        <div style={{ display: "flex", padding: "8px 12px 0", borderBottom: "1px solid var(--line)" }}>
          {useCases.map(u => (
            <Tab key={u.id} active={activeUC === u.id} onClick={() => setActiveUC(u.id)}>
              {u.name.split(" in ")[0]}
            </Tab>
          ))}
        </div>

        <div style={{ padding: 18 }}>
          {/* Use case header */}
          <div style={{ display: "flex", alignItems: "flex-start", gap: 14, marginBottom: 16 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 10,
              background: "var(--accent-soft)", color: "var(--accent-ink)",
              display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
            }}>
              <Icon name="target" size={20} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{uc.name}</div>
                {uc.active && <Badge tone="green" dot>Active</Badge>}
              </div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4, lineHeight: 1.5 }}>{uc.description}</div>
            </div>
          </div>

          {/* Target company description */}
          <div style={{ marginBottom: 18 }}>
            <SectionTitle right={<Button kind="ghost" size="sm" icon="edit">Edit</Button>}>Target company</SectionTitle>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 10, marginTop: 4 }}>
              <Mini label="Departments" body={uc.target.departments} />
              <Mini label="Seniority"   body={uc.target.seniority} />
              <Mini label="Geography"   body={uc.target.geo} />
            </div>
          </div>

          {/* Scoring rules */}
          <div style={{ marginBottom: 18 }}>
            <SectionTitle right={<Button kind="ghost" size="sm" icon="plus">Add rule</Button>}>Scoring rules</SectionTitle>
            <div style={{ border: "1px solid var(--line)", borderRadius: 8, overflow: "hidden" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead>
                  <tr style={{ background: "var(--surface-2)" }}>
                    <th style={{ padding: "8px 12px", textAlign: "left", fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Field</th>
                    <th style={{ padding: "8px 12px", textAlign: "left", fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Condition</th>
                    <th style={{ padding: "8px 12px", textAlign: "right", fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Score</th>
                  </tr>
                </thead>
                <tbody>
                  {uc.scoringRules.map((r, i) => (
                    <tr key={i} style={{ borderTop: "1px solid var(--line)" }}>
                      <td className="mono" style={{ padding: "8px 12px", color: "var(--ink-2)" }}>{r[0]}</td>
                      <td className="mono" style={{ padding: "8px 12px", color: "var(--ink-3)" }}>{r[1]}</td>
                      <td className="mono num" style={{ padding: "8px 12px", color: "var(--green-ink)", textAlign: "right", fontWeight: 600 }}>{r[2]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Buyer personas */}
          <div>
            <SectionTitle right={<Button kind="primary" size="sm" icon="user-plus">Add persona</Button>}>
              Buyer personas
              <span className="mono num" style={{ marginLeft: 8, color: "var(--ink-4)", fontWeight: 500 }}>{uc.personas.length}</span>
            </SectionTitle>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {uc.personas.map(p => <PersonaCard key={p.id} persona={p} />)}
              <button style={{
                padding: 14, borderRadius: 10,
                border: "1.5px dashed var(--line-strong)",
                background: "transparent", color: "var(--ink-3)",
                fontSize: 12.5, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                transition: "border-color 120ms, color 120ms, background 120ms",
              }}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.color = "var(--accent-ink)"; e.currentTarget.style.background = "var(--accent-soft)"; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.color = "var(--ink-3)"; e.currentTarget.style.background = "transparent"; }}
              >
                <Icon name="user-plus" size={14} />
                Add another buyer persona
              </button>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

function PersonaCard({ persona }) {
  return (
    <div style={{
      background: "var(--surface)",
      border: "1px solid var(--line)",
      borderRadius: 10,
      overflow: "hidden",
    }}>
      {/* Identity header */}
      <div style={{
        padding: "14px 16px",
        display: "flex", alignItems: "flex-start", gap: 12,
        borderBottom: "1px solid var(--line)",
        background: "var(--surface-2)",
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: "50%",
          background: window.colorFromString(persona.name),
          color: "rgba(20,20,20,0.85)",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontWeight: 600, fontSize: 14, flexShrink: 0,
          boxShadow: "inset 0 0 0 1px rgba(0,0,0,0.06)",
        }}>
          <Icon name="user" size={18} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", letterSpacing: "-0.005em" }}>{persona.name}</div>
            <Badge tone="violet" size="sm">{persona.department}</Badge>
            <Badge tone="blue" size="sm">{persona.seniority}</Badge>
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4, lineHeight: 1.5 }}>{persona.description}</div>
        </div>
        <div style={{ display: "flex", gap: 4, flexShrink: 0 }}>
          <IconButton icon="edit" title="Edit persona" />
          <IconButton icon="more-horizontal" title="More" />
        </div>
      </div>

      {/* Attribute grid */}
      <div style={{ padding: 14, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 16 }}>
        <PersonaAttr icon="alert"     label="Pain points"     items={persona.painPoints}  tone="warm" />
        <PersonaAttr icon="lightbulb" label="Interests"       items={persona.interests}   tone="blue" />
        <PersonaAttr icon="tag"       label="Keywords"        items={persona.keywords}    tone="neutral" mono />
        <PersonaAttr icon="sparkles"  label="Solutions we offer" items={persona.solutions} tone="green" />
      </div>
    </div>
  );
}

function AdminProducts() {
  return (
    <Card padding={0}>
      <div style={{ padding: 18, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Products catalog</h3>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
            The products your AI copilot draws from when drafting outreach and handling objections.
          </div>
        </div>
        <Button kind="secondary" size="md" icon="sparkles" style={{ color: "var(--accent)" }}>Train copilot</Button>
        <Button kind="primary" size="md" icon="plus">New product</Button>
      </div>
      <div style={{ padding: 16 }}>
        <ProductsList />
      </div>
    </Card>
  );
}

function AdminCompetitors() {
  return (
    <Card padding={0}>
      <div style={{ padding: 18, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Competitors</h3>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
            How you position against each competitor. Powers AI-suggested objection handling.
          </div>
        </div>
        <Button kind="secondary" size="md" icon="sparkles" style={{ color: "var(--accent)" }}>Train copilot</Button>
        <Button kind="primary" size="md" icon="plus">New competitor</Button>
      </div>
      <div style={{ padding: 16 }}>
        <CompetitorsList />
      </div>
    </Card>
  );
}

const PRODUCTS = [
  {
    id: "p-platform", name: "AI ABM CRM Platform", category: "Platform", status: "GA",
    description: "Company-centric CRM combining relationship intelligence, omnichannel outreach, AI insights and sales orchestration.",
    pricing: "From €120 / seat / month",
    targetUseCases: ["ABM execution", "LinkedIn prospecting", "Stakeholder mapping", "High-touch sales"],
    differentiators: ["Company-first CRM model", "Unified conversation workspace", "AI next-best actions", "LinkedIn relationship intelligence"],
    features: ["Omni-channel inbox", "Buying committee mapping", "AI account briefs", "Pipeline kanban"],
  },
  {
    id: "p-relate", name: "Relationship Graph", category: "Module", status: "GA",
    description: "Continuously synced LinkedIn relationship layer across the team — see who already knows whom across target accounts.",
    pricing: "Included with Premium · €40 / seat add-on on Standard",
    targetUseCases: ["Warm intros", "Multi-threaded outreach", "Champion detection"],
    differentiators: ["Cross-team graph view", "Unipile sync", "Invite-state awareness"],
    features: ["Live LinkedIn sync", "Pending/accepted tracking", "Graph search"],
  },
  {
    id: "p-copilot", name: "Sales Copilot", category: "AI Add-on", status: "Beta",
    description: "On-demand AI for drafting outreach, summarizing accounts, recommending next steps and surfacing weak buying signals.",
    pricing: "€60 / seat / month",
    targetUseCases: ["Personalized outreach", "Meeting prep", "Account briefs", "Risk detection"],
    differentiators: ["Trained on your messaging framework", "Grounded in your knowledge base", "Inline rewrites"],
    features: ["Drafting", "Summaries", "Next-best-action", "Risk alerts"],
  },
];

const COMPETITORS = [
  {
    id: "c-sf", name: "Salesforce Sales Cloud", category: "Incumbent CRM", logoTone: "blue",
    strengths: ["Mature platform", "Wide ecosystem", "Reporting depth"],
    weaknesses: ["Contact-centric, not account-centric", "Slow to set up", "Limited LinkedIn integration"],
    ourPosition: "BusinessTeam is the ABM execution layer alongside Salesforce — we add company-centric workflows, LinkedIn relationship intelligence and AI-personalized outreach without ripping out the system of record.",
    winRate: 0.61, dealsLast90: 14,
    objections: [
      { q: "We already have Salesforce", a: "Most customers keep SFDC as the system of record. BusinessTeam plugs in and runs ABM execution + outreach on top." },
      { q: "Aren't you just another CRM?", a: "We're company-first by design. The unit of work is the account, not the contact. The conversation workspace is the centerpiece." },
    ],
  },
  {
    id: "c-hubspot", name: "HubSpot Sales Hub", category: "All-in-one growth", logoTone: "warm",
    strengths: ["Easy onboarding", "Marketing integration", "SMB friendly"],
    weaknesses: ["Weak for enterprise ABM", "Limited stakeholder mapping", "No LinkedIn relationship layer"],
    ourPosition: "HubSpot wins inbound + SMB. BusinessTeam wins multi-stakeholder, high-touch B2B selling where mapping buying committees and orchestrating teams matters.",
    winRate: 0.74, dealsLast90: 9,
    objections: [
      { q: "HubSpot's cheaper", a: "True for SMB. At enterprise sizes, our ABM-specific feature set replaces 3+ point tools, which usually nets out lower TCO." },
    ],
  },
  {
    id: "c-apollo", name: "Apollo.io", category: "Sales engagement", logoTone: "violet",
    strengths: ["Large contact database", "Cold outreach automation", "Aggressive pricing"],
    weaknesses: ["Spammy reputation", "Light on relationship intelligence", "No multi-channel workspace"],
    ourPosition: "Apollo is for high-volume cold outreach. BusinessTeam is for premium, relationship-driven, multi-channel motions where personalization and warm intros matter.",
    winRate: 0.68, dealsLast90: 11,
    objections: [
      { q: "Apollo has more contacts", a: "Volume isn't the bottleneck for enterprise ABM — context and warm relationships are. We focus there." },
    ],
  },
  {
    id: "c-linsn", name: "LinkedIn Sales Navigator", category: "Prospecting tool", logoTone: "blue",
    strengths: ["Best-in-class LinkedIn data", "Brand trust"],
    weaknesses: ["Not a CRM", "No team orchestration", "Manual workflow"],
    ourPosition: "Sales Navigator is a great input layer. BusinessTeam adds team coordination, multi-channel execution, AI orchestration and a CRM around it.",
    winRate: 0.81, dealsLast90: 6,
    objections: [],
  },
];

function ProductsList() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(360px, 1fr))", gap: 12 }}>
      {PRODUCTS.map(p => <ProductCard key={p.id} p={p} />)}
      <button style={{
        padding: 16, borderRadius: 12,
        border: "1.5px dashed var(--line-strong)",
        background: "transparent", color: "var(--ink-3)",
        fontSize: 12.5, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
        minHeight: 200,
        transition: "border-color 120ms, color 120ms, background 120ms",
      }}
        onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.color = "var(--accent-ink)"; e.currentTarget.style.background = "var(--accent-soft)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.color = "var(--ink-3)"; e.currentTarget.style.background = "transparent"; }}
      >
        <Icon name="plus" size={14} /> Add a product
      </button>
    </div>
  );
}

function ProductCard({ p }) {
  return (
    <div style={{
      background: "var(--surface)",
      border: "1px solid var(--line)",
      borderRadius: 12,
      padding: 16,
      display: "flex", flexDirection: "column", gap: 10,
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 9,
          background: "var(--accent-soft)", color: "var(--accent-ink)",
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
        }}>
          <Icon name="briefcase" size={17} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{p.name}</div>
            <Badge tone={p.status === "GA" ? "green" : "warm"} dot size="sm">{p.status}</Badge>
          </div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{p.category} · <span className="mono">{p.pricing}</span></div>
        </div>
        <IconButton icon="more-horizontal" />
      </div>

      <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{p.description}</div>

      <PersonaAttr icon="target"   label="Target use cases"   items={p.targetUseCases}  tone="blue" />
      <PersonaAttr icon="sparkles" label="Differentiators"    items={p.differentiators} tone="violet" />
      <PersonaAttr icon="check"    label="Key features"       items={p.features}        tone="green" />
    </div>
  );
}

function CompetitorsList() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {COMPETITORS.map(c => <CompetitorCard key={c.id} c={c} />)}
    </div>
  );
}

function CompetitorCard({ c }) {
  const [expanded, setExpanded] = useStateMisc(false);
  const tone = c.logoTone || "neutral";
  const toneInk = ({ blue: "var(--blue)", warm: "var(--warm)", violet: "var(--accent)", neutral: "var(--ink-3)" })[tone];
  const toneSoft = ({ blue: "var(--blue-soft)", warm: "var(--warm-soft)", violet: "var(--accent-soft)", neutral: "var(--inset)" })[tone];

  return (
    <div style={{
      background: "var(--surface)",
      border: "1px solid var(--line)",
      borderRadius: 12,
      overflow: "hidden",
    }}>
      {/* Header */}
      <div style={{ padding: 16, display: "flex", alignItems: "flex-start", gap: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 10,
          background: toneSoft, color: toneInk,
          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
          fontWeight: 700, fontSize: 14,
        }}>
          {c.name.split(/\s+/).slice(0, 2).map(w => w[0]).join("")}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{c.name}</div>
            <Badge tone="neutral" size="sm">{c.category}</Badge>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 4, lineHeight: 1.55 }}>{c.ourPosition}</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6, flexShrink: 0 }}>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 10.5, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>Win rate (90d)</div>
            <div className="mono num" style={{ fontSize: 18, fontWeight: 600, color: c.winRate >= 0.5 ? "var(--green-ink)" : "var(--red-ink)" }}>
              {Math.round(c.winRate * 100)}%
            </div>
            <div style={{ fontSize: 10.5, color: "var(--ink-3)" }} className="mono">{c.dealsLast90} deals</div>
          </div>
        </div>
      </div>

      {/* Quick attributes */}
      <div style={{ padding: "0 16px 16px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <PersonaAttr icon="trending-up"   label="Their strengths"     items={c.strengths}  tone="warm" />
        <PersonaAttr icon="sparkles"      label="Where we win"        items={c.weaknesses} tone="green" />
      </div>

      {/* Battlecard / objections */}
      {c.objections.length > 0 && (
        <div style={{ borderTop: "1px solid var(--line)", background: "var(--surface-2)" }}>
          <button onClick={() => setExpanded(e => !e)} style={{
            padding: "10px 16px", width: "100%",
            display: "flex", alignItems: "center", gap: 8, textAlign: "left",
            fontSize: 12.5, fontWeight: 600, color: "var(--ink)",
          }}>
            <Icon name="shield" size={13} style={{ color: "var(--accent)" }} />
            Battlecard
            <span className="mono num" style={{ color: "var(--ink-4)", fontWeight: 500 }}>{c.objections.length} objection{c.objections.length === 1 ? "" : "s"}</span>
            <span style={{ flex: 1 }} />
            <Icon name={expanded ? "chevron-up" : "chevron-down"} size={12} style={{ color: "var(--ink-3)" }} />
          </button>
          {expanded && (
            <div style={{ padding: "4px 16px 16px", display: "flex", flexDirection: "column", gap: 12 }}>
              {c.objections.map((o, i) => (
                <div key={i}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--warm-ink)", display: "flex", alignItems: "center", gap: 5 }}>
                    <Icon name="message-circle" size={11} />
                    "{o.q}"
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 4, lineHeight: 1.55, paddingLeft: 16 }}>
                    <span style={{ color: "var(--accent)", fontWeight: 600, marginRight: 4 }}>→</span>{o.a}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function PersonaAttr({ icon, label, items, tone, mono }) {
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 5, marginBottom: 7 }}>
        <Icon name={icon} size={11} style={{ color: ({ warm: "var(--warm)", blue: "var(--blue)", neutral: "var(--ink-3)", green: "var(--green)" })[tone] }} />
        <span style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</span>
        <span className="mono num" style={{ fontSize: 10.5, color: "var(--ink-4)" }}>{items.length}</span>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
        {items.map((it, i) => (
          <Badge key={i} tone={tone} size="sm">
            {mono ? <span className="mono">{it}</span> : it}
          </Badge>
        ))}
      </div>
    </div>
  );
}

function AdminTeam() {
  /* Per-user channel connection state — keyed by userId */
  const CHANNEL_STATES = {
    "guy-lansing-0030809": { linkedin: "connected", email: "needs_reconnect", calendar: "not_connected", whatsapp: "not_connected" },
    "sales-lead-demo":     { linkedin: "not_connected", email: "connected",   calendar: "connected",     whatsapp: "not_connected" },
    "amelie-nadeau":       { linkedin: "connected",     email: "connected",   calendar: "connected",     whatsapp: "not_connected" },
    "rohan-kapoor":        { linkedin: "not_connected", email: "not_connected", calendar: "not_connected", whatsapp: "not_connected" },
  };

  const [teams, setTeams] = useStateMisc([
    { id: "revenue",    name: "Revenue",          tone: "violet", lead: "guy-lansing-0030809", description: "Core revenue org" },
    { id: "enterprise", name: "Enterprise Sales", tone: "blue",   lead: "amelie-nadeau",       description: "Strategic accounts > €100k ARR" },
    { id: "outbound",   name: "Outbound",         tone: "warm",   lead: "rohan-kapoor",        description: "Pipeline generation & ABM" },
  ]);
  const [members, setMembers] = useStateMisc(window.USERS);
  const [editing, setEditing] = useStateMisc(null); /* "create" | teamId | null */
  const [newName, setNewName] = useStateMisc("");
  const [newTone, setNewTone] = useStateMisc("green");

  const memberCountFor = (teamName) => members.filter(m => m.team === teamName).length;

  const handleCreateTeam = () => {
    const name = newName.trim();
    if (!name) return;
    const id = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
    setTeams(prev => [...prev, { id, name, tone: newTone, description: "" }]);
    setNewName(""); setNewTone("green"); setEditing(null);
  };
  const handleDeleteTeam = (teamId) => {
    setTeams(prev => prev.filter(t => t.id !== teamId));
    setEditing(null);
  };
  const assignMemberTeam = (memberId, teamName) => {
    setMembers(prev => prev.map(m => m.id === memberId ? { ...m, team: teamName } : m));
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {/* Members header + stats */}
      <Card padding={0}>
        <div style={{ padding: 18, display: "flex", alignItems: "center", gap: 12, borderBottom: "1px solid var(--line)" }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Team members</h3>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
              Each member's connected accounts power outreach, sync and AI personalization.
            </div>
          </div>
          <Button kind="secondary" size="md" icon="filter">Filter</Button>
          <Button kind="primary" size="md" icon="user-plus">Invite member</Button>
        </div>

        {/* Stats strip */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))" }}>
          {[
            ["Members",   members.length, null],
            ["LinkedIn",  Object.values(CHANNEL_STATES).filter(c => c.linkedin === "connected").length + " / " + members.length, "connected"],
            ["Email",     Object.values(CHANNEL_STATES).filter(c => c.email === "connected").length + " / " + members.length, "needs"],
            ["Calendar",  Object.values(CHANNEL_STATES).filter(c => c.calendar === "connected").length + " / " + members.length, null],
            ["WhatsApp",  Object.values(CHANNEL_STATES).filter(c => c.whatsapp === "connected").length + " / " + members.length, null],
          ].map(([label, value, hint], i, arr) => (
            <div key={label} style={{
              padding: "14px 18px",
              borderRight: i < arr.length - 1 ? "1px solid var(--line)" : "none",
              borderBottom: "1px solid var(--line)",
            }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</div>
              <div className="mono num" style={{ fontSize: 18, fontWeight: 600, color: "var(--ink)", marginTop: 2 }}>{value}</div>
              {hint === "needs" && <div style={{ fontSize: 10.5, color: "var(--warm-ink)", marginTop: 1, display: "inline-flex", alignItems: "center", gap: 3 }}>
                <Icon name="alert" size={9} /> 1 reconnection
              </div>}
            </div>
          ))}
        </div>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(340px, 1fr))", gap: 14 }}>
        {members.map(u => (
          <MemberCard
            key={u.id} user={u}
            channels={CHANNEL_STATES[u.id] || {}}
            teams={teams}
            onAssignTeam={(name) => assignMemberTeam(u.id, name)}
          />
        ))}

        {/* Invite slot */}
        <button style={{
          padding: 20,
          border: "1.5px dashed var(--line-strong)",
          borderRadius: 12,
          background: "transparent",
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
          gap: 10, color: "var(--ink-3)",
          transition: "border-color 120ms, background 120ms",
          minHeight: 220,
        }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent)"; e.currentTarget.style.background = "var(--accent-soft)"; e.currentTarget.style.color = "var(--accent-ink)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink-3)"; }}
        >
          <div style={{
            width: 40, height: 40, borderRadius: "50%",
            border: "1.5px dashed currentColor",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <Icon name="user-plus" size={16} />
          </div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Invite a member</div>
          <div style={{ fontSize: 12 }}>{10 - members.length} of 10 seats available</div>
        </button>
      </div>

      {/* Teams card — last */}
      <Card padding={0}>
        <div style={{ padding: 18, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Teams</h3>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 2 }}>
              Group members into teams to scope dashboards, pipelines and quotas.
            </div>
          </div>
          {editing !== "create" && (
            <Button kind="primary" size="md" icon="plus" onClick={() => setEditing("create")}>Create team</Button>
          )}
        </div>

        {/* Create team inline form */}
        {editing === "create" && (
          <div style={{ padding: 16, background: "var(--surface-2)", borderBottom: "1px solid var(--line)" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 200px auto auto", gap: 10, alignItems: "flex-end" }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 5 }}>Team name</div>
                <input
                  autoFocus value={newName} onChange={(e) => setNewName(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter") handleCreateTeam(); if (e.key === "Escape") setEditing(null); }}
                  placeholder="e.g. EMEA Mid-Market"
                  style={{
                    width: "100%", padding: "8px 10px", fontSize: 13,
                    background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 7,
                    color: "var(--ink)", outline: "none",
                  }} />
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 5 }}>Color</div>
                <div style={{ display: "flex", gap: 4 }}>
                  {["violet","blue","green","warm","red","neutral"].map(t => (
                    <button key={t} onClick={() => setNewTone(t)} title={t} style={{
                      width: 28, height: 28, borderRadius: "50%",
                      background: ({ violet: "var(--accent)", blue: "var(--blue)", green: "var(--green)", warm: "var(--warm)", red: "var(--red)", neutral: "var(--ink-4)" })[t],
                      border: newTone === t ? "2px solid var(--ink)" : "2px solid transparent",
                      boxShadow: "inset 0 0 0 1px rgba(0,0,0,0.06)",
                    }} />
                  ))}
                </div>
              </div>
              <Button kind="secondary" size="md" onClick={() => setEditing(null)}>Cancel</Button>
              <Button kind="primary"   size="md" icon="check" onClick={handleCreateTeam}>Create team</Button>
            </div>
          </div>
        )}

        <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 10 }}>
          {teams.map(team => {
            const leadUser = members.find(m => m.id === team.lead);
            const teamMembers = members.filter(m => m.team === team.name);
            return (
              <div key={team.id} style={{
                padding: 14, borderRadius: 10,
                border: "1px solid var(--line)", background: "var(--surface)",
                display: "flex", flexDirection: "column", gap: 10,
              }}>
                <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
                  <span style={{
                    width: 10, height: 10, borderRadius: "50%", marginTop: 4,
                    background: ({ violet: "var(--accent)", blue: "var(--blue)", green: "var(--green)", warm: "var(--warm)", red: "var(--red)", neutral: "var(--ink-4)" })[team.tone],
                    boxShadow: "0 0 0 3px color-mix(in oklch, " + ({ violet: "var(--accent)", blue: "var(--blue)", green: "var(--green)", warm: "var(--warm)", red: "var(--red)", neutral: "var(--ink-4)" })[team.tone] + " 20%, transparent)",
                  }} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{team.name}</div>
                    {team.description && <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{team.description}</div>}
                  </div>
                  <button onClick={() => handleDeleteTeam(team.id)} title="Delete team" style={{ color: "var(--ink-4)", padding: 2 }}>
                    <Icon name="trash" size={13} />
                  </button>
                </div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 8, borderTop: "1px solid var(--line)" }}>
                  <div style={{ display: "flex", alignItems: "center" }}>
                    {teamMembers.slice(0, 5).map((m, i) => (
                      <div key={m.id} style={{ marginLeft: i > 0 ? -6 : 0, border: "2px solid var(--surface)", borderRadius: "50%" }}>
                        <Avatar name={m.name} size={22} title={m.name} />
                      </div>
                    ))}
                    {teamMembers.length === 0 && (
                      <span style={{ fontSize: 11.5, color: "var(--ink-4)", fontStyle: "italic" }}>No members yet</span>
                    )}
                    {teamMembers.length > 0 && (
                      <span className="mono num" style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: 8 }}>{teamMembers.length}</span>
                    )}
                  </div>
                  {leadUser && (
                    <div style={{ fontSize: 10.5, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 4 }}>
                      <Icon name="star" size={10} style={{ color: "var(--warm)" }} />
                      Lead: {leadUser.name.split(" ")[0]}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}

/* Business-card style member card */
function MemberCard({ user, channels, teams, onAssignTeam }) {
  const [picking, setPicking] = useStateMisc(false);
  const [avatarUrl, setAvatarUrl] = useStateMisc(user.avatarUrl || null);
  const [openChannel, setOpenChannel] = useStateMisc(null); /* "linkedin" | "email" | "calendar" | "whatsapp" | null */
  const cardRef = React.useRef(null);
  const fileRef = React.useRef(null);

  React.useEffect(() => {
    if (!picking) return;
    const onClick = (e) => { if (!cardRef.current?.contains(e.target)) setPicking(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, [picking]);

  const handleFile = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => setAvatarUrl(reader.result);
    reader.readAsDataURL(f);
    e.target.value = "";
  };

  const currentTeam = teams?.find(t => t.name === user.team);
  const dotColor = currentTeam
    ? ({ violet: "var(--accent)", blue: "var(--blue)", green: "var(--green)", warm: "var(--warm)", red: "var(--red)", neutral: "var(--ink-4)" })[currentTeam.tone]
    : "var(--ink-4)";

  return (
    <div ref={cardRef} style={{
      position: "relative",
      background: "var(--surface)",
      border: "1px solid var(--line)",
      borderRadius: 12,
      boxShadow: "var(--shadow-1)",
      overflow: "hidden",
      display: "flex", flexDirection: "column",
    }}>
      {/* Top "stripe" — soft brand gradient */}
      <div style={{
        height: 56,
        background: `linear-gradient(115deg, ${window.colorFromString(user.name)}, oklch(0.92 0.04 80))`,
        borderBottom: "1px solid var(--line)",
        position: "relative",
      }}>
        <div style={{ position: "absolute", top: 10, right: 10 }}>
          <IconButton icon="more-horizontal" title="Actions" />
        </div>
      </div>

      {/* Identity */}
      <div style={{ padding: "0 16px", marginTop: -28, position: "relative" }}>
        <div
          onClick={() => fileRef.current?.click()}
          title="Change profile picture"
          style={{
            width: 56, height: 56, borderRadius: "50%",
            border: "3px solid var(--surface)", overflow: "hidden",
            background: "var(--surface)",
            position: "relative", cursor: "pointer",
            display: "inline-block",
          }}
        >
          <Avatar name={user.name} src={avatarUrl} size={50} />
          <div
            className="avatar-edit-overlay"
            style={{
              position: "absolute", inset: 0,
              borderRadius: "50%",
              display: "flex", alignItems: "center", justifyContent: "center",
              background: "color-mix(in oklch, oklch(0.2 0 0) 55%, transparent)",
              color: "#fff",
              opacity: 0,
              transition: "opacity 140ms ease",
            }}
          >
            <Icon name="image" size={16} />
          </div>
          <style>{`
            div[title="Change profile picture"]:hover .avatar-edit-overlay { opacity: 1; }
          `}</style>
        </div>
        <input
          ref={fileRef}
          type="file"
          accept="image/*"
          style={{ display: "none" }}
          onChange={handleFile}
        />
      </div>

      <div style={{ padding: "8px 16px 0", flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <h4 style={{ margin: 0, fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em" }}>{user.name}</h4>
          {user.id === CURRENT_USER.id && <Badge tone="violet" size="sm">You</Badge>}
        </div>
        {user.title && (
          <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 2, fontWeight: 500 }}>
            {user.title}
          </div>
        )}

        {/* Team chip — clickable, opens picker */}
        <div style={{ position: "relative", marginTop: 8, display: "inline-block" }}>
          <button
            onClick={() => setPicking(p => !p)}
            style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              padding: "3px 8px 3px 8px",
              fontSize: 11.5, fontWeight: 500,
              color: "var(--ink-2)",
              background: "var(--inset)",
              border: "1px solid var(--line)",
              borderRadius: 999,
              transition: "background 120ms, border-color 120ms",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface-2)"; e.currentTarget.style.borderColor = "var(--line-strong)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "var(--inset)"; e.currentTarget.style.borderColor = "var(--line)"; }}
          >
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: dotColor }} />
            <span>{user.team || "Unassigned"}</span>
            <Icon name="chevron-down" size={10} style={{ color: "var(--ink-4)" }} />
          </button>

          {picking && (
            <div style={{
              position: "absolute", top: "calc(100% + 6px)", left: 0,
              minWidth: 220, zIndex: 20,
              background: "var(--surface)",
              border: "1px solid var(--line-strong)",
              borderRadius: 8,
              boxShadow: "var(--shadow-3)",
              padding: 4, overflow: "hidden",
            }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", padding: "8px 10px 4px" }}>
                Assign team
              </div>
              {teams.map(t => (
                <button key={t.id} onClick={() => { onAssignTeam(t.name); setPicking(false); }}
                  style={{
                    display: "flex", alignItems: "center", gap: 8,
                    padding: "7px 10px", width: "100%", textAlign: "left",
                    borderRadius: 5, fontSize: 12.5,
                    background: user.team === t.name ? "var(--inset)" : "transparent",
                    color: "var(--ink)",
                  }}
                  onMouseEnter={(e) => { if (user.team !== t.name) e.currentTarget.style.background = "var(--surface-2)"; }}
                  onMouseLeave={(e) => { if (user.team !== t.name) e.currentTarget.style.background = "transparent"; }}
                >
                  <span style={{ width: 8, height: 8, borderRadius: "50%", background: ({ violet: "var(--accent)", blue: "var(--blue)", green: "var(--green)", warm: "var(--warm)", red: "var(--red)", neutral: "var(--ink-4)" })[t.tone] }} />
                  <span style={{ flex: 1 }}>{t.name}</span>
                  {user.team === t.name && <Icon name="check" size={12} stroke={2.4} />}
                </button>
              ))}
              <div style={{ height: 1, background: "var(--line)", margin: "4px 0" }} />
              <button onClick={() => { onAssignTeam(""); setPicking(false); }}
                style={{
                  display: "flex", alignItems: "center", gap: 8,
                  padding: "7px 10px", width: "100%", textAlign: "left",
                  borderRadius: 5, fontSize: 12, color: "var(--ink-3)",
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
              >
                <Icon name="x" size={11} stroke={2.2} />
                Remove from team
              </button>
            </div>
          )}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 3, marginTop: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--ink-3)" }}>
            <Icon name="mail" size={11} style={{ color: "var(--ink-4)" }} />
            <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.email}</span>
          </div>
          {user.phone && (
            <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--ink-3)" }} className="mono">
              <Icon name="phone" size={11} style={{ color: "var(--ink-4)" }} />
              <span>{user.phone}</span>
            </div>
          )}
        </div>
        <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
          <Badge tone={user.role === "Admin" ? "warm" : "neutral"} size="sm">{user.role}</Badge>
          <Badge tone="green" dot size="sm">Active</Badge>
        </div>
      </div>

      {/* Channel connections */}
      <div style={{ padding: 16, marginTop: 16, borderTop: "1px solid var(--line)", background: "var(--surface-2)" }}>
        <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 8 }}>
          Connected accounts
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
          <ChannelChip name="LinkedIn" icon="linkedin"        status={channels.linkedin || "not_connected"} active={openChannel === "linkedin"} onClick={() => setOpenChannel(openChannel === "linkedin" ? null : "linkedin")} />
          <ChannelChip name="Email"    icon="mail"            status={channels.email    || "not_connected"} active={openChannel === "email"}    onClick={() => setOpenChannel(openChannel === "email"    ? null : "email")} />
          <ChannelChip name="Calendar" icon="calendar"        status={channels.calendar || "not_connected"} active={openChannel === "calendar"} onClick={() => setOpenChannel(openChannel === "calendar" ? null : "calendar")} />
          <ChannelChip name="WhatsApp" icon="message-circle"  status={channels.whatsapp || "not_connected"} active={openChannel === "whatsapp"} onClick={() => setOpenChannel(openChannel === "whatsapp" ? null : "whatsapp")} />
        </div>

        {openChannel && (
          <div style={{
            marginTop: 12, padding: 12,
            background: "var(--surface)",
            border: "1px solid var(--line)",
            borderRadius: 8,
            animation: "fadein 180ms ease",
          }}>
            <ChannelPanel channel={openChannel} status={channels[openChannel] || "not_connected"} user={user} onClose={() => setOpenChannel(null)} />
          </div>
        )}
      </div>
    </div>
  );
}

/* Per-channel chip — color + dot + label encode state */
function ChannelChip({ name, icon, status, active, onClick }) {
  const conf = {
    connected:       { dot: "var(--green)",  bg: "var(--green-soft)", border: "color-mix(in oklch, var(--green) 25%, transparent)", label: "Linked",   fg: "var(--green-ink)" },
    needs_reconnect: { dot: "var(--red)",    bg: "var(--red-soft)",   border: "color-mix(in oklch, var(--red) 25%, transparent)",   label: "Reconnect", fg: "var(--red-ink)"   },
    not_connected:   { dot: "var(--ink-5)",  bg: "var(--inset)",      border: "var(--line)",                                         label: "Not linked",fg: "var(--ink-3)"     },
  }[status];

  return (
    <button
      onClick={onClick}
      title={`${name} · ${conf.label}`}
      style={{
        padding: "8px 6px",
        background: conf.bg, color: conf.fg,
        border: `1px solid ${active ? "var(--ink)" : conf.border}`,
        outline: active ? "2px solid color-mix(in oklch, var(--accent) 30%, transparent)" : "none",
        outlineOffset: -1,
        borderRadius: 8,
        display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
        cursor: "pointer", textAlign: "center",
        transition: "transform 120ms, box-shadow 120ms, border-color 120ms",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-1px)"; e.currentTarget.style.boxShadow = "var(--shadow-1)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = "none"; }}
    >
      <div style={{ position: "relative", display: "inline-flex" }}>
        <Icon name={icon} size={15} />
        <span style={{
          position: "absolute", top: -2, right: -3,
          width: 7, height: 7, borderRadius: "50%",
          background: conf.dot,
          boxShadow: "0 0 0 1.5px var(--surface)",
        }} />
      </div>
      <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: 0 }}>{name}</span>
    </button>
  );
}

/* Channel configuration panel — appears beneath the chip row when a chip is active. */
function ChannelPanel({ channel, status, user, onClose }) {
  const connected = status === "connected";
  const needsReconnect = status === "needs_reconnect";

  const Header = ({ title, hint }) => (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 8, marginBottom: 10 }}>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)" }}>{title}</div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2, lineHeight: 1.45 }}>{hint}</div>
      </div>
      <button onClick={onClose} title="Close" style={{
        width: 22, height: 22, borderRadius: 5,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        color: "var(--ink-3)",
      }}
        onMouseEnter={(e) => e.currentTarget.style.background = "var(--inset)"}
        onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
      ><Icon name="x" size={11} /></button>
    </div>
  );

  const StatusRow = () => (
    <div style={{
      display: "flex", alignItems: "center", gap: 8,
      padding: "6px 10px",
      borderRadius: 6,
      background: needsReconnect ? "var(--red-soft)" : connected ? "var(--green-soft)" : "var(--inset)",
      color: needsReconnect ? "var(--red-ink)" : connected ? "var(--green-ink)" : "var(--ink-3)",
      fontSize: 11.5, marginBottom: 10,
    }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: "currentColor" }} />
      {needsReconnect ? "Authentication expired — please reconnect."
        : connected ? "Connected and syncing."
        : "Not connected."}
    </div>
  );

  if (channel === "linkedin") {
    return (
      <>
        <Header
          title="LinkedIn account"
          hint="Used for outreach, relationship sync and invitation campaigns."
        />
        <StatusRow />
        {connected || needsReconnect ? (
          <>
            <ChannelKV k="Provider"   v="Unipile" />
            <ChannelKV k="Account ID" v={<span className="mono">ktnY30WMQkSy587…</span>} />
            <ChannelKV k="Profile"    v={<a className="mono" style={{ color: "var(--blue-ink)" }}>linkedin.com/in/{user.id.split("-")[0]}</a>} />
            <ChannelKV k="Daily invite cap" v={<input defaultValue="40" type="number" style={kvInput} />} />
            <ChannelKV k="Auto-personalize" v={<MiniToggle defaultOn />} />
            <div style={panelActions}>
              {needsReconnect && <Button kind="primary" size="sm" icon="refresh">Reconnect</Button>}
              <Button size="sm" icon="refresh">Sync now</Button>
              <Button size="sm" kind="danger" icon="x">Disconnect</Button>
            </div>
          </>
        ) : (
          <ConnectViaProvider provider="Unipile" />
        )}
      </>
    );
  }

  if (channel === "email") {
    return (
      <>
        <Header
          title="Email account"
          hint="Sends and threads outbound email. Required for email outreach."
        />
        <StatusRow />
        {(connected || needsReconnect) ? (
          <>
            <ChannelKV k="Provider"      v="Google Workspace" />
            <ChannelKV k="Email address" v={<span className="mono">{user.email}</span>} />
            <ChannelKV k="Display name"  v={<input defaultValue={user.name} style={kvInput} />} />
            <ChannelKV k="Reply-to"      v={<input defaultValue={user.email} style={kvInput} />} />
            <ChannelKV k="Signature"     v={<MiniToggle defaultOn />} />
            <ChannelKV k="Track opens"   v={<MiniToggle defaultOn />} />
            <ChannelKV k="Track clicks"  v={<MiniToggle />} />
            <div style={panelActions}>
              {needsReconnect && <Button kind="primary" size="sm" icon="refresh">Reconnect</Button>}
              <Button size="sm" icon="refresh">Sync inbox</Button>
              <Button size="sm" kind="danger" icon="x">Disconnect</Button>
            </div>
          </>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            <Button kind="primary" size="sm" icon="mail">Connect Google</Button>
            <Button kind="secondary" size="sm" icon="mail">Connect Outlook</Button>
            <Button kind="ghost" size="sm" icon="settings" style={{ gridColumn: "1 / -1" }}>Use SMTP/IMAP…</Button>
          </div>
        )}
      </>
    );
  }

  if (channel === "calendar") {
    return (
      <>
        <Header
          title="Calendar account"
          hint="Surfaces availability, books meetings and syncs events."
        />
        <StatusRow />
        {(connected || needsReconnect) ? (
          <>
            <ChannelKV k="Provider"  v="Google Calendar" />
            <ChannelKV k="Account"   v={<span className="mono">{user.email}</span>} />
            <ChannelKV k="Timezone"  v={<select defaultValue="Europe/Madrid" style={kvSelect}>
              <option>Europe/Madrid</option><option>Europe/London</option><option>America/New_York</option><option>Asia/Singapore</option>
            </select>} />
            <ChannelKV k="Working hours" v={
              <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                <input defaultValue="09:00" style={{ ...kvInput, width: 64 }} />
                <span style={{ color: "var(--ink-4)" }}>—</span>
                <input defaultValue="18:00" style={{ ...kvInput, width: 64 }} />
              </span>
            } />
            <ChannelKV k="Auto-create meeting links" v={<MiniToggle defaultOn />} />
            <div style={panelActions}>
              {needsReconnect && <Button kind="primary" size="sm" icon="refresh">Reconnect</Button>}
              <Button size="sm" icon="refresh">Sync events</Button>
              <Button size="sm" kind="danger" icon="x">Disconnect</Button>
            </div>
          </>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            <Button kind="primary" size="sm" icon="calendar">Connect Google</Button>
            <Button kind="secondary" size="sm" icon="calendar">Connect Outlook</Button>
          </div>
        )}
      </>
    );
  }

  if (channel === "whatsapp") {
    return (
      <>
        <Header
          title="WhatsApp Business"
          hint="Two-way messaging with prospects who opt in. Requires a verified business number."
        />
        <StatusRow />
        {(connected || needsReconnect) ? (
          <>
            <ChannelKV k="Phone number"   v={<span className="mono">+34 600 12 34 56</span>} />
            <ChannelKV k="Display name"   v={<input defaultValue="BusinessTeam · Guy" style={kvInput} />} />
            <ChannelKV k="Auto-replies"   v={<MiniToggle />} />
            <ChannelKV k="Business hours" v={<MiniToggle defaultOn />} />
            <div style={panelActions}>
              {needsReconnect && <Button kind="primary" size="sm" icon="refresh">Reconnect</Button>}
              <Button size="sm" kind="danger" icon="x">Disconnect</Button>
            </div>
          </>
        ) : (
          <>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 10 }}>
              <div>
                <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 4 }}>Business phone number</div>
                <div style={{ display: "flex", gap: 6 }}>
                  <select defaultValue="+34" style={{ ...kvSelect, width: 72 }}>
                    <option>+34</option><option>+33</option><option>+44</option><option>+1</option>
                  </select>
                  <input placeholder="600 12 34 56" style={{ ...kvInput, flex: 1 }} />
                </div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 4 }}>Display name</div>
                <input placeholder="BusinessTeam · Guy" style={kvInput} />
              </div>
            </div>
            <Button kind="primary" size="sm" icon="message-circle">Send verification code</Button>
          </>
        )}
      </>
    );
  }
  return null;
}

const kvInput = {
  padding: "5px 8px", fontSize: 12,
  background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 5,
  color: "var(--ink)", outline: "none", width: "100%",
  fontFamily: "inherit",
};
const kvSelect = {
  ...kvInput, appearance: "none",
  backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round'><path d='M6 9l6 6 6-6'/></svg>\")",
  backgroundRepeat: "no-repeat",
  backgroundPosition: "right 6px center",
  paddingRight: 22,
};
const panelActions = {
  display: "flex", gap: 6, marginTop: 10, paddingTop: 10,
  borderTop: "1px solid var(--line)",
  flexWrap: "wrap",
};

function ChannelKV({ k, v }) {
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "100px 1fr",
      gap: 10, alignItems: "center",
      padding: "5px 0",
      fontSize: 12,
    }}>
      <span style={{ color: "var(--ink-3)" }}>{k}</span>
      <span style={{ color: "var(--ink)", display: "flex", alignItems: "center", gap: 6 }}>{v}</span>
    </div>
  );
}

function MiniToggle({ defaultOn }) {
  const [on, setOn] = React.useState(!!defaultOn);
  return (
    <button onClick={() => setOn(o => !o)} style={{
      width: 28, height: 16, borderRadius: 999,
      background: on ? "var(--accent)" : "var(--line-strong)",
      padding: 2, transition: "background 160ms",
    }}>
      <span style={{
        width: 12, height: 12, borderRadius: "50%", background: "#fff",
        transform: on ? "translateX(12px)" : "translateX(0)",
        transition: "transform 160ms cubic-bezier(0.2, 0.7, 0.2, 1)",
        boxShadow: "0 1px 2px rgba(0,0,0,0.18)",
      }} />
    </button>
  );
}

function ConnectViaProvider({ provider }) {
  return (
    <div style={{
      padding: 14, border: "1px dashed var(--line-strong)",
      borderRadius: 8, textAlign: "center",
      color: "var(--ink-3)",
    }}>
      <div style={{ fontSize: 12, marginBottom: 8 }}>Connect via <b style={{ color: "var(--ink-2)" }}>{provider}</b> to enable this channel.</div>
      <Button kind="primary" size="sm" icon="link">Connect</Button>
    </div>
  );
}

function AdminIntegrations() {
  const items = [
    { id: "li",  channel: "LinkedIn",      via: "Unipile",          status: "connected", icon: "linkedin", acct: "ktnY30WMQkSy5872oubphw" },
    { id: "em",  channel: "Email",         via: "Gmail",            status: "not_connected", icon: "mail" },
    { id: "ca",  channel: "Calendar",      via: "Google Calendar",  status: "not_connected", icon: "calendar" },
    { id: "wa",  channel: "WhatsApp",      via: "WhatsApp Business",status: "not_connected", icon: "message-circle" },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 14 }}>
      {items.map(it => (
        <Card key={it.id} padding={18}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--inset)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name={it.icon} size={16} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{it.channel}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>via {it.via}</div>
            </div>
            {it.status === "connected"
              ? <Badge tone="green" dot>Connected</Badge>
              : <Badge tone="neutral" dot>Not connected</Badge>}
          </div>
          {it.acct && (
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", padding: "6px 8px", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 6 }}>
              acct {it.acct.slice(0, 14)}…
            </div>
          )}
          <div style={{ marginTop: 12 }}>
            {it.status === "connected"
              ? <Button kind="secondary" size="sm" icon="refresh">Sync now</Button>
              : <Button kind="primary" size="sm" icon="link">Connect</Button>}
          </div>
        </Card>
      ))}
    </div>
  );
}

function AdminAI() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {[
        { id: "ren",     name: "Role enrichment", purpose: "Infer department + seniority from current position titles.", model: "GPT-4o · 0.99 confidence avg", updated: "2026-05-19T20:52:58Z" },
        { id: "outr",    name: "Outreach draft", purpose: "Personalized LinkedIn / email drafts using account + contact context.", model: "GPT-4o · custom prompt", updated: null },
        { id: "summ",    name: "Account summarizer", purpose: "Synthesize conversations and signals into account briefs.", model: "GPT-4o", updated: "2026-05-20T07:02:00Z" },
        { id: "nba",     name: "Next-best-action", purpose: "Recommend the highest-impact action for each contact / account.", model: "GPT-4o", updated: "2026-05-20T07:02:00Z" },
      ].map(a => (
        <Card key={a.id} padding={16}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent-ink)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="sparkles" size={16} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 14, fontWeight: 600 }}>{a.name}</span>
                <Badge tone="green" dot>Live</Badge>
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{a.purpose}</div>
              <div style={{ display: "flex", gap: 14, marginTop: 8, fontSize: 11, color: "var(--ink-3)" }} className="mono">
                <span>{a.model}</span>
                <span>·</span>
                <span>Updated {a.updated ? fmtRelative(a.updated) : "never"}</span>
              </div>
            </div>
            <Button size="sm" icon="edit">Edit prompt</Button>
          </div>
        </Card>
      ))}
    </div>
  );
}

function AdminNotifications() {
  const [channels, setChannels] = useStateMisc({
    in_app: true, email: true, push: false, slack: false,
  });
  const [digest, setDigest] = useStateMisc("realtime");  /* realtime | daily | weekly */
  const [quietHours, setQuietHours] = useStateMisc(true);

  const initialPrefs = {
    mention:         { inApp: true,  email: true,  push: true,  slack: false },
    reply:           { inApp: true,  email: true,  push: true,  slack: false },
    li_accepted:     { inApp: true,  email: false, push: true,  slack: false },
    account_change:  { inApp: true,  email: false, push: false, slack: false },
    stage_change:    { inApp: true,  email: true,  push: false, slack: true  },
    task_due:        { inApp: true,  email: true,  push: true,  slack: false },
    task_overdue:    { inApp: true,  email: true,  push: true,  slack: true  },
    sync_issue:      { inApp: true,  email: true,  push: false, slack: true  },
    ai_recommend:    { inApp: true,  email: false, push: false, slack: false },
    weak_signal:     { inApp: true,  email: false, push: false, slack: false },
    team_note:       { inApp: true,  email: false, push: false, slack: false },
  };
  const [prefs, setPrefs] = useStateMisc(initialPrefs);

  const togglePref = (event, channel) => {
    setPrefs(prev => ({ ...prev, [event]: { ...prev[event], [channel]: !prev[event][channel] }}));
  };

  const EVENT_GROUPS = [
    { id: "conversations", title: "Conversations & relationships", icon: "messages", events: [
      ["mention",     "I'm mentioned in a note or thread",   "Direct mentions by teammates."],
      ["reply",       "A prospect replies",                  "Incoming reply on any channel."],
      ["li_accepted", "LinkedIn invitation accepted",        "A new prospect connects."],
      ["team_note",   "Teammate adds a note on my account",  "Internal collaboration signal."],
    ]},
    { id: "accounts", title: "Accounts & pipeline", icon: "building", events: [
      ["account_change", "Account lifecycle changes",       "Target → Engaged, Engaged → Opportunity, etc."],
      ["stage_change",   "Opportunity stage moves",         "Pipeline progression on owned opportunities."],
    ]},
    { id: "tasks", title: "Tasks & execution", icon: "check-square", events: [
      ["task_due",     "Task due today",        "Morning reminder for active tasks."],
      ["task_overdue", "Task overdue",          "An assigned task missed its deadline."],
      ["sync_issue",   "Sync or integration issue", "LinkedIn / email / calendar disconnects."],
    ]},
    { id: "ai", title: "AI &amp; signals", icon: "sparkles", events: [
      ["ai_recommend", "AI recommends an action",  "Next-best-action surfaces a high-impact suggestion."],
      ["weak_signal",  "Weak buying signal detected", "Profile view, content engagement, job change, etc."],
    ]},
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {/* Delivery channels */}
      <Card padding={0}>
        <div style={{ padding: 18, borderBottom: "1px solid var(--line)" }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Delivery channels</h3>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>
            Where notifications are sent. The matrix below uses these channels per-event.
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))" }}>
          {[
            ["in_app", "In-app",    "Inbox + bell badge",         "messages", true],
            ["email",  "Email",     "guy.lansing@nelc.es",        "mail",     true],
            ["push",   "Push",      "Mobile app on iOS",          "phone",    false],
            ["slack",  "Slack",     "Connect to receive in Slack","link",     false],
          ].map(([key, label, hint, icon, available], i, arr) => (
            <div key={key} style={{
              padding: "14px 18px",
              borderRight: i < arr.length - 1 ? "1px solid var(--line)" : "none",
              display: "flex", alignItems: "center", gap: 12,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 8,
                background: channels[key] ? "var(--accent-soft)" : "var(--inset)",
                color: channels[key] ? "var(--accent-ink)" : "var(--ink-3)",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <Icon name={icon} size={16} />
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{label}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{hint}</div>
              </div>
              {available ? (
                <Toggle on={channels[key]} onChange={() => setChannels(prev => ({ ...prev, [key]: !prev[key] }))} />
              ) : (
                <Button size="sm" kind="ghost">Connect</Button>
              )}
            </div>
          ))}
        </div>
      </Card>

      {/* Notification matrix */}
      <Card padding={0}>
        <div style={{ padding: 18, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center" }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Notification preferences</h3>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>
              Pick which channels you want for each event. Channels you've turned off above are disabled.
            </div>
          </div>
          <Button size="md" kind="ghost">Reset to defaults</Button>
        </div>

        {/* Matrix header */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 80px 80px 80px 80px",
          padding: "10px 18px",
          fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)",
          textTransform: "uppercase", letterSpacing: "0.04em",
          background: "var(--surface-2)",
          borderBottom: "1px solid var(--line)",
          alignItems: "center",
        }}>
          <div>Event</div>
          <div style={{ textAlign: "center" }}>In-app</div>
          <div style={{ textAlign: "center" }}>Email</div>
          <div style={{ textAlign: "center" }}>Push</div>
          <div style={{ textAlign: "center" }}>Slack</div>
        </div>

        {EVENT_GROUPS.map((group, gi) => (
          <React.Fragment key={group.id}>
            <div style={{
              padding: "10px 18px",
              background: "var(--surface-2)",
              borderTop: gi > 0 ? "1px solid var(--line)" : "none",
              borderBottom: "1px solid var(--line)",
              fontSize: 11, fontWeight: 600, color: "var(--ink-2)",
              display: "flex", alignItems: "center", gap: 6,
            }}>
              <Icon name={group.icon} size={12} style={{ color: "var(--ink-3)" }} />
              {group.title}
            </div>
            {group.events.map(([eventId, title, hint], i, arr) => (
              <div key={eventId} style={{
                display: "grid",
                gridTemplateColumns: "1fr 80px 80px 80px 80px",
                padding: "12px 18px",
                borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
                alignItems: "center",
              }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>{title}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>{hint}</div>
                </div>
                {["inApp", "email", "push", "slack"].map((ch, idx) => {
                  const chKey = ["in_app", "email", "push", "slack"][idx];
                  const channelOn = channels[chKey];
                  const cellOn = prefs[eventId]?.[ch];
                  return (
                    <div key={ch} style={{ display: "flex", justifyContent: "center" }}>
                      <Toggle
                        on={cellOn && channelOn}
                        disabled={!channelOn}
                        onChange={() => channelOn && togglePref(eventId, ch)}
                      />
                    </div>
                  );
                })}
              </div>
            ))}
          </React.Fragment>
        ))}
      </Card>

      {/* Digest + quiet hours */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 14 }}>
        <Card padding={18}>
          <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Delivery cadence</h3>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>How often the inbox + email rolls up notifications.</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 12 }}>
            {[
              { id: "realtime", label: "Real-time",       hint: "Notify as events happen." },
              { id: "daily",    label: "Daily digest",    hint: "Roll up once each morning (08:00)." },
              { id: "weekly",   label: "Weekly summary",  hint: "Monday morning rollup." },
            ].map(o => (
              <button key={o.id} onClick={() => setDigest(o.id)} style={{
                display: "flex", alignItems: "flex-start", gap: 10,
                padding: 10, borderRadius: 8,
                background: digest === o.id ? "var(--accent-soft)" : "var(--surface-2)",
                border: digest === o.id ? "1px solid color-mix(in oklch, var(--accent) 25%, transparent)" : "1px solid var(--line)",
                textAlign: "left",
              }}>
                <span style={{
                  width: 14, height: 14, borderRadius: "50%", marginTop: 1,
                  border: digest === o.id ? "4px solid var(--accent)" : "1.5px solid var(--line-strong)",
                  background: "var(--surface)",
                  flexShrink: 0,
                }} />
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>{o.label}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>{o.hint}</div>
                </div>
              </button>
            ))}
          </div>
        </Card>

        <Card padding={18}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
            <div style={{ flex: 1 }}>
              <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Quiet hours</h3>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>Mute push + email during these hours. Critical alerts always go through.</div>
            </div>
            <Toggle on={quietHours} onChange={() => setQuietHours(q => !q)} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginTop: 14, opacity: quietHours ? 1 : 0.5 }}>
            <Field label="From" value="20:00" compact />
            <Field label="Until" value="07:30" compact />
            <Field label="Timezone" value="Europe/Madrid" compact />
          </div>
          <div style={{ marginTop: 14, padding: 10, background: "var(--inset)", border: "1px solid var(--line)", borderRadius: 7, fontSize: 12, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 6 }}>
            <Icon name="shield" size={12} style={{ color: "var(--accent)" }} />
            Critical events (reply from prospect, sync down) bypass quiet hours.
          </div>
        </Card>
      </div>
    </div>
  );
}

/* Reusable toggle */
function Toggle({ on, onChange, disabled }) {
  return (
    <button
      onClick={(e) => { e.preventDefault(); if (!disabled) onChange?.(); }}
      disabled={disabled}
      style={{
        width: 32, height: 18, borderRadius: 999,
        background: disabled ? "var(--inset)" : (on ? "var(--accent)" : "var(--line-strong)"),
        padding: 2, transition: "background 160ms",
        cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.45 : 1,
        display: "inline-flex", alignItems: "center",
        flexShrink: 0,
      }}
    >
      <span style={{
        width: 14, height: 14, borderRadius: "50%",
        background: "#fff",
        transform: on ? "translateX(14px)" : "translateX(0)",
        transition: "transform 160ms cubic-bezier(0.2, 0.7, 0.2, 1)",
        boxShadow: "0 1px 2px rgba(0,0,0,0.18)",
      }} />
    </button>
  );
}

function AdminBilling() {
  return (
    <Card padding={24}>
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 24 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>Current plan</div>
          <div style={{ fontSize: 22, fontWeight: 600, marginTop: 2, letterSpacing: "-0.015em" }}>Premium</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Renews 31 Dec 2026</div>
        </div>
        <Button kind="secondary" size="md">Manage plan</Button>
        <Button kind="ghost" size="md">View invoices</Button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12 }}>
        <Mini label="Seats" body={<span><b className="num">3</b> of 10 used</span>} />
        <Mini label="Status" body={<Badge tone="green" dot>Active</Badge>} />
        <Mini label="Next invoice" body="€840.00 · 1 Jun" />
      </div>
    </Card>
  );
}

function AdminSecurity() {
  return (
    <Card padding={24}>
      <div style={{ fontSize: 16, fontWeight: 600 }}>Security</div>
      <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>Session, SSO and audit settings for the workspace.</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12, marginTop: 20 }}>
        <Mini label="SSO" body="Not configured" />
        <Mini label="2FA enforcement" body="Optional" />
        <Mini label="Session length" body="30 days" />
        <Mini label="Audit log retention" body="90 days" />
      </div>
    </Card>
  );
}

function Field({ label, value, multiline, icon, compact, placeholder, onChange }) {
  const controlled = typeof onChange === "function";
  const commonProps = controlled
    ? { value: value || "", onChange: (e) => onChange(e.target.value) }
    : { defaultValue: value };
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 5, display: "flex", alignItems: "center", gap: 5 }}>
        {icon && <Icon name={icon} size={11} />}
        {label}
      </div>
      {multiline ? (
        <textarea {...commonProps} placeholder={placeholder} style={{
          width: "100%", padding: 10, fontSize: 13, lineHeight: 1.5,
          minHeight: 70, resize: "vertical",
          background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 7,
          color: "var(--ink)", fontFamily: "inherit", outline: "none",
        }} />
      ) : (
        <input {...commonProps} placeholder={placeholder} style={{
          width: "100%", padding: compact ? "6px 8px" : "8px 10px", fontSize: 13,
          background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 7,
          color: "var(--ink)", outline: "none",
        }} />
      )}
    </div>
  );
}

function Mini({ label, body }) {
  return (
    <div style={{ padding: 12, background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 8 }}>
      <div style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>{label}</div>
      <div style={{ fontSize: 13, color: "var(--ink)", marginTop: 4, fontWeight: 500 }}>{body}</div>
    </div>
  );
}

Object.assign(window, {
  PageCalendar, PageTasks, TasksList, PageContent, PageKnowledge, PageAutomation, PageAdmin,
  EventDetailModal,
});
