/* ===========================================================================
   launch-integrations.jsx — Two-way project-manager sync (ClickUp · Asana ·
   Trello · Basecamp). Mounts inside Settings → Integrations and exposes a
   per-task send control. Reads/writes the `pmIntegrations` fold seam.
   Components → window: PMIntegrations, TaskSyncControl.
   =========================================================================== */
const { Section: PMSection, act: pmAct, ENGINE_LABELS: PM_ENG, ENGINE_COLORS: PM_ENGC } = window;

const RECON_TYPES = {
  conflict: { label: "Conflict",        color: "#E0B638" },
  inbound:  { label: "New in tool",     color: "#10B5C7" },
  outbound: { label: "Not pushed",      color: "#7A4FBF" },
  deleted:  { label: "Removed in tool", color: "#F25BA7" },
  unmapped: { label: "Unmapped",        color: "var(--pvt-text-dim)" },
};

const PM_DIRS = [ { id: "push", label: "Push" }, { id: "two-way", label: "Two-way" }, { id: "pull", label: "Pull" } ];
const PM_FREQ = { realtime: "Real-time", "15m": "Every 15 min", hourly: "Hourly", manual: "Manual" };
const PM_MAP_ROWS = [
  { key: "root",      lcc: "Workspace root", hint: "The launch maps to one…" },
  { key: "engines",   lcc: "Engines",        hint: "Six operating engines" },
  { key: "tasks",     lcc: "Tasks",          hint: "This-week task board" },
  { key: "pipelines", lcc: "Pipelines",      hint: "Inquiry → Advanced" },
  { key: "timeline",  lcc: "Timeline",       hint: "Production weeks" },
];
const PM_SCOPE_ROWS = [
  { key: "tasks",     label: "Tasks & status",  sub: "Two-way task + status sync" },
  { key: "engines",   label: "Engines",         sub: "Group tasks by engine" },
  { key: "pipelines", label: "Pipelines",       sub: "Stage board cards" },
  { key: "timeline",  label: "Timeline",        sub: "Milestone schedule" },
];

/* Brand monogram tile (no external logos). */
function PMMark({ pm, size = 38 }) {
  return (
    <span style={{ width: size, height: size, borderRadius: 10, flexShrink: 0, display: "grid", placeItems: "center",
      background: "color-mix(in srgb, " + pm.color + " 22%, var(--pvt-surface))", border: "1px solid " + pm.color,
      color: pm.color, fontFamily: "var(--pvt-font-display)", fontWeight: 700, fontSize: size * 0.42 }}>
      {pm.name[0]}
    </span>
  );
}

function PMStatusChip({ pm }) {
  const tone = pm.connected ? "#10B5C7" : "var(--pvt-text-dim)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 10.5, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.05em", color: tone }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: pm.connected ? "#10B5C7" : "var(--pvt-border)" }} />
      {pm.connected ? "Connected" : "Not connected"}
    </span>
  );
}

/* Small segmented control. */
function PMSeg({ value, options, onChange }) {
  return (
    <div style={{ display: "inline-flex", background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: 999, padding: 3, gap: 2 }}>
      {options.map((o) => {
        const on = o.id === value;
        return (
          <button key={o.id} onClick={() => onChange(o.id)} style={{ border: 0, cursor: "pointer", borderRadius: 999, padding: "6px 14px", fontSize: 12, fontWeight: 700, fontFamily: "var(--pvt-font-body)",
            background: on ? "var(--role-accent)" : "transparent", color: on ? "#fff" : "var(--pvt-muted)" }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function PMToggle({ on, onClick }) {
  return (
    <button onClick={onClick} title="Toggle" style={{ width: 42, height: 24, borderRadius: 999, border: 0, cursor: "pointer", padding: 3, background: on ? "var(--role-accent)" : "var(--pvt-surface-light)", display: "flex", justifyContent: on ? "flex-end" : "flex-start", transition: "background 140ms" }}>
      <span style={{ width: 18, height: 18, borderRadius: "50%", background: "#fff" }} />
    </button>
  );
}

/* ---------------------------------------------------------------------------
   Configuration slide-over for one connector.
   --------------------------------------------------------------------------- */
function PMConfigDrawer({ pm, onClose, patch }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);
  if (!pm) return null;
  const conflictOpts = { lcc: "LCC wins", platform: pm.name + " wins", recent: "Most recent wins" };
  const connect = () => patch(pm.id, pm.connected
    ? { connected: false, account: "", who: "", lastSync: "—" }
    : { connected: true, account: "ARGT 2026", who: "kam@argt.com", lastSync: "just now", log: [{ at: "just now", dir: "out", text: "Connected " + pm.name + " · initial sync queued" }, ...(pm.log || [])] });
  const syncNow = () => { patch(pm.id, { lastSync: "just now", log: [{ at: "just now", dir: "out", text: "Manual sync — pushed 8 tasks, pulled 2 updates" }, ...(pm.log || [])] }); if (window.argtPing) window.argtPing(pm.name + " synced just now"); };
  const setMap = (k, v) => patch(pm.id, { mapping: { ...pm.mapping, [k]: v } });
  const setScope = (k) => patch(pm.id, { scope: { ...pm.scope, [k]: !pm.scope[k] } });

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 540, background: "rgba(8,6,18,0.55)", backdropFilter: "blur(4px)", display: "flex", justifyContent: "flex-end" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(500px, 96vw)", height: "100%", background: "var(--pvt-surface-raised)", borderLeft: "1px solid var(--pvt-border-light)", boxShadow: "-32px 0 80px rgba(0,0,0,0.5)", display: "flex", flexDirection: "column", animation: "lccDrawerIn 220ms ease" }}>
        {/* header */}
        <div style={{ padding: "20px 22px 16px", borderBottom: "1px solid var(--pvt-border-light)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <PMMark pm={pm} size={42} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 19 }}>{pm.name}</div>
              <div style={{ fontSize: 11.5, color: "var(--pvt-text-dim)" }}>{pm.hierarchy}</div>
            </div>
            <button onClick={onClose} title="Close" style={{ background: "none", border: 0, color: "var(--pvt-text-dim)", fontSize: 24, cursor: "pointer", lineHeight: 1 }}>×</button>
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 14 }}>
            <PMStatusChip pm={pm} />
            <button className="pill" onClick={connect} style={pm.connected ? { color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" } : { background: "var(--role-accent)", color: "#fff", borderColor: "var(--role-accent)" }}>{pm.connected ? "Disconnect" : "Connect"}</button>
          </div>
          {pm.connected && <div style={{ fontSize: 11.5, color: "var(--pvt-text-dim)", marginTop: 8 }}>{pm.account} · {pm.who} · last sync {pm.lastSync}</div>}
        </div>

        {/* body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "18px 22px", display: "flex", flexDirection: "column", gap: 22, opacity: pm.connected ? 1 : 0.5, pointerEvents: pm.connected ? "auto" : "none" }}>
          {/* direction */}
          <div>
            <div className="pm-h">Sync direction</div>
            <PMSeg value={pm.direction} options={PM_DIRS} onChange={(v) => patch(pm.id, { direction: v })} />
            <p style={{ margin: "8px 0 0", fontSize: 11.5, color: "var(--pvt-text-dim)", lineHeight: 1.45 }}>
              {pm.direction === "two-way" ? "Changes flow both ways. Edits here push out; edits in " + pm.name + " pull back in." : pm.direction === "push" ? "LCC is the source of truth — changes push out to " + pm.name + " only." : pm.name + " is the source of truth — changes pull into LCC only."}
            </p>
          </div>

          {/* what syncs */}
          <div>
            <div className="pm-h">What syncs</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {PM_SCOPE_ROWS.map((r) => (
                <div key={r.key} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 12, alignItems: "center" }}>
                  <div><div style={{ fontSize: 13, color: "var(--pvt-text)" }}>{r.label}</div><div style={{ fontSize: 11, color: "var(--pvt-text-dim)", marginTop: 1 }}>{r.sub}</div></div>
                  <PMToggle on={!!pm.scope[r.key]} onClick={() => setScope(r.key)} />
                </div>
              ))}
            </div>
          </div>

          {/* mapping — group LCC surfaces onto the platform's native hierarchy */}
          <div>
            <div className="pm-h">Mapping · how LCC groups into {pm.name}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {PM_MAP_ROWS.map((row) => (
                <div key={row.key} style={{ display: "grid", gridTemplateColumns: "1fr 18px 150px", gap: 10, alignItems: "center", background: "var(--pvt-surface-mid)", borderRadius: "var(--r-md)", padding: "9px 12px", opacity: row.key !== "root" && pm.scope[row.key] === false ? 0.45 : 1 }}>
                  <div style={{ minWidth: 0 }}><div style={{ fontSize: 12.5, fontFamily: "var(--pvt-font-display)" }}>{row.lcc}</div><div style={{ fontSize: 10.5, color: "var(--pvt-text-dim)" }}>{row.hint}</div></div>
                  <span style={{ color: "var(--pvt-text-dim)", textAlign: "center" }}>→</span>
                  <select value={pm.mapping[row.key]} onChange={(e) => setMap(row.key, e.target.value)} style={{ background: "var(--pvt-surface)", border: "1px solid var(--pvt-border-light)", borderRadius: 8, color: "var(--pvt-text)", padding: "7px 9px", fontSize: 12, fontFamily: "var(--pvt-font-body)", outline: "none", width: "100%" }}>
                    {pm.containers.map((c) => <option key={c} value={c}>{c}</option>)}
                  </select>
                </div>
              ))}
            </div>
          </div>

          {/* cadence + conflict */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <div className="pm-h">Frequency</div>
              <select value={pm.frequency} onChange={(e) => patch(pm.id, { frequency: e.target.value })} style={pmSelStyle()}>
                {Object.entries(PM_FREQ).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
            <div>
              <div className="pm-h">On conflict</div>
              <select value={pm.conflict} onChange={(e) => patch(pm.id, { conflict: e.target.value })} style={pmSelStyle()}>
                {Object.entries(conflictOpts).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
          </div>

          {/* activity */}
          <div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <div className="pm-h" style={{ margin: 0 }}>Sync activity</div>
              <button className="pill active" onClick={syncNow}>Sync now</button>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {(pm.log || []).map((l, i) => (
                <div key={i} style={{ display: "flex", gap: 10, padding: "9px 6px", borderRadius: 8, alignItems: "flex-start" }}>
                  <span title={l.dir === "in" ? "Pulled in" : "Pushed out"} style={{ fontSize: 12, fontWeight: 800, color: l.dir === "in" ? "#10B5C7" : "var(--role-accent-bright)", width: 16, textAlign: "center", flexShrink: 0 }}>{l.dir === "in" ? "↓" : "↑"}</span>
                  <div style={{ minWidth: 0 }}><div style={{ fontSize: 12.5, color: "var(--pvt-text)", lineHeight: 1.35 }}>{l.text}</div><div style={{ fontSize: 10.5, color: "var(--pvt-text-dim)", marginTop: 1 }}>{l.at}</div></div>
                </div>
              ))}
              {(!pm.log || pm.log.length === 0) && <div style={{ padding: 14, textAlign: "center", fontSize: 12, color: "var(--pvt-text-dim)" }}>No sync activity yet.</div>}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
function pmSelStyle() { return { background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", color: "var(--pvt-text)", padding: "10px 12px", fontSize: 13, fontFamily: "var(--pvt-font-body)", outline: "none", width: "100%" }; }

/* ---------------------------------------------------------------------------
   Manager — grid of connectors, mounted in Settings → Integrations.
   --------------------------------------------------------------------------- */
function PMIntegrations() {
  const [list, setList] = window.useDB("pmIntegrations");
  const [recon] = window.useDB("pmReconcile");
  const [open, setOpen] = React.useState(null);
  const patch = (id, fields) => setList((xs) => xs.map((p) => p.id === id ? { ...p, ...fields } : p));
  const reconBy = (k) => recon.filter((r) => r.platform === k).length;
  const connectedCount = list.filter((p) => p.connected).length;
  const syncAll = () => { setList((xs) => xs.map((p) => p.connected ? { ...p, lastSync: "just now" } : p)); if (window.argtPing) window.argtPing("Synced all connected tools"); };
  const active = open ? list.find((p) => p.id === open) : null;

  return (
    <React.Fragment>
      <PMSection title="Project-manager sync" action={<div style={{ display: "flex", gap: 8, alignItems: "center" }}><span className="micro">{connectedCount}/{list.length} CONNECTED · 2-WAY</span><button className="pill" onClick={syncAll}>Sync all now</button></div>}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
          {list.map((pm) => (
            <div key={pm.id} onClick={() => setOpen(pm.id)} title={"Configure " + pm.name}
                 style={{ background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", padding: 16, display: "flex", flexDirection: "column", gap: 12, cursor: "pointer", transition: "border-color 140ms, transform 140ms" }}
                 onMouseEnter={(e) => { e.currentTarget.style.borderColor = pm.color; e.currentTarget.style.transform = "translateY(-2px)"; }}
                 onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--pvt-border-light)"; e.currentTarget.style.transform = "none"; }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <PMMark pm={pm} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15 }}>{pm.name}</div>
                  <div style={{ fontSize: 11, color: "var(--pvt-text-dim)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{pm.hierarchy}</div>
                </div>
              </div>
              <PMStatusChip pm={pm} />
              {reconBy(pm.key) > 0 && <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, fontWeight: 700, color: "#E0B638" }}><span style={{ width: 6, height: 6, borderRadius: "50%", background: "#E0B638" }} />{reconBy(pm.key)} to reconcile</span>}
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "auto", paddingTop: 4 }}>
                <span style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{pm.connected ? "Synced " + pm.lastSync : "Set up sync"}</span>
                <span className="pill" style={{ pointerEvents: "none", fontSize: 12 }}>{pm.connected ? "Configure" : "Connect"}</span>
              </div>
            </div>
          ))}
        </div>
        <PMConfigDrawer pm={active} onClose={() => setOpen(null)} patch={patch} />
      </PMSection>
      <PMReconcile />
    </React.Fragment>
  );
}

/* ---------------------------------------------------------------------------
   Per-task send/sync control — drops into the task edit modal.
   --------------------------------------------------------------------------- */
function TaskSyncControl({ task, setTask }) {
  const [list] = window.useDB("pmIntegrations");
  const connected = list.filter((p) => p.connected);
  const sync = task && task.sync;
  const sendTo = (pm) => { setTask((t) => ({ ...t, sync: { key: pm.key, name: pm.name, color: pm.color, mapped: pm.mapping.tasks, at: "just now" } })); if (window.argtPing) window.argtPing("Task sent to " + pm.name + " as a " + pm.mapping.tasks); };
  const openExt = () => { if (window.argtPing) window.argtPing("Opening task in " + sync.name); };
  const unlink = () => setTask((t) => { const n = { ...t }; delete n.sync; return n; });

  return (
    <div style={{ background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", padding: "12px 14px" }}>
      <div style={{ fontSize: 11, color: "var(--pvt-text-dim)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 700, marginBottom: 10 }}>Project-manager sync</div>
      {connected.length === 0 ? (
        <div style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>No tools connected. Connect one in Settings → Integrations.</div>
      ) : sync ? (
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
            <span style={{ width: 9, height: 9, borderRadius: 3, background: sync.color }} />
            Synced to <strong style={{ fontWeight: 700 }}>{sync.name}</strong>{sync.mapped ? <span style={{ color: "var(--pvt-text-dim)" }}> · {sync.mapped}</span> : null}
          </span>
          <span style={{ display: "flex", gap: 8, marginLeft: "auto" }}>
            <button className="pill" onClick={openExt}>Open ↗</button>
            <button className="pill" onClick={unlink} style={{ color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Unlink</button>
          </span>
        </div>
      ) : (
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <span style={{ fontSize: 12.5, color: "var(--pvt-muted)" }}>Send to</span>
          {connected.map((pm) => (
            <button key={pm.id} onClick={() => sendTo(pm)} className="pill" style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
              <span style={{ width: 9, height: 9, borderRadius: 3, background: pm.color }} />{pm.name}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Reconciliation queue — divergences a two-way sync can't auto-resolve.
   Lives on the integrations page, below the connector grid.
   --------------------------------------------------------------------------- */
function ReconRow({ item, pm, onResolve }) {
  const meta = RECON_TYPES[item.type] || RECON_TYPES.unmapped;
  const [mapEngine, setMapEngine] = React.useState("content");
  const engLabel = item.engine ? (PM_ENG[item.engine] || item.engine) : null;
  const name = pm ? pm.name : item.platform;
  const color = pm ? pm.color : "var(--pvt-text-dim)";

  const actions = {
    conflict: [ { l: "Keep LCC", k: "keep-lcc" }, { l: "Keep " + name, k: "keep-ext" } ],
    inbound:  [ { l: "Import to LCC", k: "import", primary: true }, { l: "Ignore", k: "ignore", dim: true } ],
    outbound: [ { l: "Push to " + name, k: "push", primary: true }, { l: "Skip", k: "skip", dim: true } ],
    deleted:  [ { l: "Delete in LCC", k: "delete", danger: true }, { l: "Restore in " + name, k: "restore" } ],
    unmapped: [ { l: "Map + import", k: "map", primary: true }, { l: "Ignore", k: "ignore", dim: true } ],
  }[item.type] || [];

  return (
    <div className="stat-row" style={{ display: "flex", flexDirection: "column", gap: 12, padding: "14px 16px", alignItems: "stretch" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <span style={{ width: 10, height: 10, borderRadius: 3, background: color, flexShrink: 0 }} />
        <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 14 }}>{item.taskTitle}</span>
        <span style={{ fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.05em", color: meta.color, border: "1px solid " + meta.color, borderRadius: 999, padding: "2px 8px" }}>{meta.label}</span>
        {engLabel && <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--pvt-text-dim)" }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: PM_ENGC[item.engine] || "var(--pvt-muted)" }} />{engLabel}</span>}
        <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--pvt-text-dim)" }}>{name} · {item.detected}</span>
      </div>

      {item.type === "conflict" && item.fields ? (
        <div style={{ display: "grid", gridTemplateColumns: "110px 1fr 1fr", gap: 1, background: "var(--pvt-border-light)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
          <div style={{ ...reconCell(), color: "var(--pvt-text-dim)", fontWeight: 700, fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em" }}>Field</div>
          <div style={{ ...reconCell(), color: "var(--pvt-text-dim)", fontWeight: 700, fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em" }}>LCC</div>
          <div style={{ ...reconCell(), color: "var(--pvt-text-dim)", fontWeight: 700, fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em" }}>{name}</div>
          {item.fields.map((f, i) => (
            <React.Fragment key={i}>
              <div style={{ ...reconCell(), color: "var(--pvt-muted)" }}>{f.label}</div>
              <div style={{ ...reconCell(), color: "var(--pvt-text)" }}>{f.lcc}</div>
              <div style={{ ...reconCell(), color: f.lcc !== f.ext ? "#E0B638" : "var(--pvt-text)" }}>{f.ext}</div>
            </React.Fragment>
          ))}
        </div>
      ) : (
        <div style={{ fontSize: 12.5, color: "var(--pvt-muted)" }}>{item.summary}</div>
      )}

      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        {item.type === "unmapped" && (
          <select value={mapEngine} onChange={(e) => setMapEngine(e.target.value)} style={{ background: "var(--pvt-surface)", border: "1px solid var(--pvt-border-light)", borderRadius: 8, color: "var(--pvt-text)", padding: "7px 9px", fontSize: 12, fontFamily: "var(--pvt-font-body)", outline: "none" }}>
            {Object.keys(PM_ENG).map((k) => <option key={k} value={k}>{PM_ENG[k]}</option>)}
          </select>
        )}
        {actions.map((a) => (
          <button key={a.k} className={"pill" + (a.primary ? " active" : "")} onClick={() => onResolve(item, a.k, mapEngine)}
            style={a.danger ? { color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" } : a.dim ? { color: "var(--pvt-text-dim)" } : {}}>{a.l}</button>
        ))}
      </div>
    </div>
  );
}
function reconCell() { return { background: "var(--pvt-surface)", padding: "8px 12px", fontSize: 12 }; }

function PMReconcile() {
  const [recon, setRecon] = window.useDB("pmReconcile");
  const [list, setList] = window.useDB("pmIntegrations");
  const [filter, setFilter] = React.useState(null);
  const pmFor = (k) => list.find((p) => p.key === k);
  const shown = filter ? recon.filter((r) => r.platform === filter) : recon;
  const connected = list.filter((p) => p.connected);

  const resolve = (item, choice, mapEngine) => {
    const pm = pmFor(item.platform);
    const name = pm ? pm.name : item.platform;
    const msg = {
      "keep-lcc": "Kept LCC version of '" + item.taskTitle + "' · pushed to " + name,
      "keep-ext": "Accepted " + name + " version of '" + item.taskTitle + "'",
      "import":   "Imported '" + item.taskTitle + "' from " + name,
      "ignore":   "Ignored '" + item.taskTitle + "'",
      "push":     "Pushed '" + item.taskTitle + "' to " + name,
      "skip":     "Skipped '" + item.taskTitle + "'",
      "delete":   "Deleted '" + item.taskTitle + "' in LCC",
      "restore":  "Restored '" + item.taskTitle + "' in " + name,
      "map":      "Mapped '" + item.taskTitle + "' to " + (PM_ENG[mapEngine] || mapEngine) + " and imported",
    }[choice] || "Resolved";
    setRecon((xs) => xs.filter((r) => r.id !== item.id));
    if (pm) {
      const dir = (choice === "keep-lcc" || choice === "push" || choice === "restore") ? "out" : "in";
      setList((xs) => xs.map((p) => p.id === pm.id ? { ...p, log: [{ at: "just now", dir, text: msg }, ...(p.log || [])] } : p));
    }
    if (window.argtPing) window.argtPing(msg);
  };

  return (
    <PMSection title="Task reconciliation"
      action={recon.length > 0
        ? <span className="micro" style={{ color: "#E0B638" }}>{recon.length} NEED REVIEW</span>
        : <span className="micro">ALL IN SYNC</span>}>
      {recon.length > 0 && (
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 14 }}>
          <button className={"pill" + (filter === null ? " active" : "")} onClick={() => setFilter(null)}>All <span style={{ opacity: 0.7 }}>{recon.length}</span></button>
          {connected.map((pm) => {
            const n = recon.filter((r) => r.platform === pm.key).length;
            if (!n) return null;
            return <button key={pm.key} className={"pill" + (filter === pm.key ? " active" : "")} onClick={() => setFilter(pm.key)}><span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: pm.color }} />{pm.name} <span style={{ opacity: 0.7 }}>{n}</span></span></button>;
          })}
        </div>
      )}
      {shown.length > 0 ? (
        <div className="stat-rows">
          {shown.map((item) => <ReconRow key={item.id} item={item} pm={pmFor(item.platform)} onResolve={resolve} />)}
        </div>
      ) : (
        <div style={{ padding: "28px 18px", textAlign: "center" }}>
          <div style={{ fontSize: 26, color: "#10B5C7", marginBottom: 6 }}>✓</div>
          <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15 }}>Everything is in sync</div>
          <div style={{ fontSize: 12.5, color: "var(--pvt-text-dim)", marginTop: 4 }}>No conflicts or pending changes across your connected tools.</div>
        </div>
      )}
    </PMSection>
  );
}

Object.assign(window, { PMIntegrations, TaskSyncControl });
