// ============================================================================
// IMS — Admin: In Progress lists (Outreach + Collaboration)
// Scoped to role: OS and CM see the same columns but only their own rows.
// ============================================================================

function InProgressPage({ variant, completed = false }) {
  // variant: "outreach" | "collab", completed: filter collab to all-stages-done
  const { data, setPage, role, activePersonId, updateInfluencer, notify } = useApp();
  const [noteTarget, setNoteTarget] = useState(null);

  const rowsAll = variant === "outreach" ? data.outreachInProgress : data.collabInProgress;
  const rows = variant === "collab"
    ? rowsAll.filter(r => {
        if (r.deletedAt || r.stageState === "Dropped") return false;
        const stageOk = completed ? r.stageState === "Complete" : r.stageState !== "Complete";
        const personOk = role !== "admin" ? r.cmId === activePersonId : true;
        return stageOk && personOk;
      })
    : role !== "admin"
      ? rowsAll.filter(r => r.specialistId === activePersonId && !r.deletedAt && r.status !== "Dropped")
      : rowsAll.filter(r => !r.deletedAt && r.status !== "Dropped");

  const columns = variant === "outreach" ? [
    { key: "bundleId", label: "Bundle ID", accessor: r => r.bundleId },
    { key: "status", label: "Status", accessor: r => r.status },
    { key: "specialist", label: "Specialist", accessor: r => r.specialistName },
  ] : [
    { key: "bundleId", label: "Lead Bundle", accessor: r => r.bundleId },
    { key: "campaign", label: "Campaign", accessor: r => r.campaignName || "—" },
    { key: "stageStatus", label: "Stage", accessor: r => `Stage ${r.currentStage} ${r.stageState}` },
    { key: "cm", label: "Collab Manager", accessor: r => r.cmName },
    { key: "source", label: "Found By", accessor: r => r.markedInterestedBy || r.specialistName || "—" },
  ];
  const { filtered, filters, set, clear, openFor, setOpenFor, distinctFor } = useColumnFilter(rows, columns);

  const [search, setSearch] = useState("");
  const searchFiltered = useMemo(() => {
    if (!search.trim()) return filtered;
    const q = search.toLowerCase();
    return filtered.filter(r =>
      r.name.toLowerCase().includes(q) ||
      r.handle.toLowerCase().includes(q) ||
      (r.specialistName || r.cmName || "").toLowerCase().includes(q) ||
      (r.bundleId || "").toLowerCase().includes(q) ||
      (r.campaignName || "").toLowerCase().includes(q)
    );
  }, [filtered, search]);

  const [pg, setPg] = useState(1);
  const perPage = 8;
  const totalPages = Math.max(1, Math.ceil(searchFiltered.length / perPage));
  const paged = searchFiltered.slice((pg - 1) * perPage, pg * perPage);

  const title = variant === "outreach"
    ? "Outreach — In Progress"
    : completed ? "Collaboration — Completed" : "Collaboration — Active";
  const subtitle = variant === "outreach"
    ? (role === "admin"
      ? "All influencers currently assigned to outreach specialists."
      : "Your currently-assigned influencers. Click a row to progress their status.")
    : completed
      ? "All influencers who have completed all 4 collaboration stages. Payments may still be pending."
      : (role === "admin"
        ? "Influencers currently active in a collaboration manager's pipeline."
        : "Your currently-assigned potential leads, by stage.");

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>{title}</h1>
          <div className="subtitle">{subtitle}</div>
        </div>
        <div className="meta">
          <span>{searchFiltered.length} shown</span>
        </div>
      </div>

      {role === "outreach" && variant === "outreach" && <AnnouncementsChip />}

      <div className="toolbar">
        {variant === "outreach" && <KpiInline data={rows} variant="outreach" />}
        {variant === "collab" && <KpiInline data={rows} variant="collab" />}
        <div className="spacer" />
        <div className="search">
          <Ic.search />
          <input
            placeholder="Search influencer, specialist, bundle…"
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPg(1); }}
          />
          {search && <button className="search-clear" onClick={() => { setSearch(""); setPg(1); }}><Ic.x /></button>}
        </div>
      </div>

      <ActiveFilterChips filters={filters} columns={columns} onClear={clear} />

      <div className="table-wrap">
        <table className="ims">
          <thead>
            <tr>
              <th>Influencer</th>
              {columns.map(col => (
                <FilterHeader key={col.key} col={col} filters={filters} openFor={openFor} setOpenFor={setOpenFor}
                  distincts={distinctFor(col.key)} onPick={(v) => { set(col.key, v); setPg(1); }} onClear={() => { clear(col.key); setPg(1); }} />
              ))}
              {variant === "outreach" && <>
                <th className="num">Amount Owed</th>
                <th>Paid Status</th>
                <th className="num">Bonus Amount</th>
                <th>Bonus Status</th>
              </>}
              {variant === "collab" && <>
                <th>Evidence</th>
                <th>Agreement</th>
                <th>Payment</th>
              </>}
              {role === "admin" && <th style={{ width: 220 }}>Notes</th>}
            </tr>
          </thead>
          <tbody>
            {paged.length === 0 && (
              <tr><td colSpan={99} style={{ textAlign: "center", padding: "48px 0", color: "var(--ink-3)", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.06em" }}>
                NO RESULTS — try a different search or filter
              </td></tr>
            )}
            {paged.map(r => (
              <tr key={r.id} className="clickable" onClick={() => setPage({ key: "profile", influencer: r, from: variant === "outreach" ? "os-in-progress" : "cm-in-progress" })}>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <InfCell name={r.name} handle={r.handle} />
                    {r.aiFlag && <span className="warn-tri" title="AI flag: screenshot mismatch"><Ic.warn /></span>}
                    {r.previouslyRejected && <span className="pill" style={{ color: "var(--bad)", borderColor: "var(--bad-bg)", background: "var(--bad-bg)", fontSize: 10 }}>Prev. Rejected</span>}
                  </div>
                </td>
                <td><BundleIdChip id={r.bundleId} /></td>

                {variant === "outreach" && (
                  <>
                    <td><StatusChip status={r.status} /></td>
                    <td className="text-small">{r.specialistName}</td>
                    <td className="num">{r.amountOwed ? `$${r.amountOwed.toFixed(2)}` : "—"}</td>
                    <td>{r.paidStatus ? <StatusChip status={r.paidStatus} /> : <span className="text-mute">—</span>}</td>
                    <td className="num">{r.bonusAmount ? `$${r.bonusAmount.toFixed(2)}` : "—"}</td>
                    <td>{r.bonusStatus ? <StatusChip status={r.bonusStatus} /> : <span className="text-mute">—</span>}</td>
                  </>
                )}
                {variant === "collab" && (
                  <>
                    <td>{r.campaignName ? <Chip tone="info" xs>{r.campaignName}</Chip> : <span className="text-mute">—</span>}</td>
                    <td>
                      <StageBar stages={r.stages} currentStage={r.currentStage} stageState={r.stageState} />
                    </td>
                    <td className="text-small">{r.cmName}</td>
                    <td className="text-small">
                      {(r.markedInterestedBy || r.specialistName)
                        ? <span>
                            {r.markedInterestedBy || r.specialistName}
                            {r.sourceBundle && <span className="text-xs text-mute" style={{ marginLeft: 6, fontFamily: "var(--font-mono)" }}>· {r.sourceBundle}</span>}
                          </span>
                        : <span className="text-mute">—</span>}
                    </td>
                    <td className="text-mono text-xs">
                      {r.stages.filter(s => s.evidence === "Provided").length}/4 uploaded
                    </td>
                    <td className="text-mono text-xs">
                      S1-S4{r.commission ? ` · ${r.commission}` : ""}
                    </td>
                    <td>
                      <div style={{ display: "inline-flex", gap: 3 }}>
                        {r.stages.map((s, i) => (
                          <span key={i} title={`S${i+1}: ${s.paymentStatus || "—"}`} style={{
                            display: "inline-block", width: 18, height: 18, borderRadius: 3, fontSize: 9, fontFamily: "var(--font-mono)",
                            fontWeight: 600, textAlign: "center", lineHeight: "18px",
                            background: s.paymentStatus === "Paid" ? "var(--ok)" : s.paymentStatus === "Pending" ? "var(--warn)" : s.paymentStatus === "Unpaid" ? "var(--line-2)" : "var(--line)",
                            color: s.paymentStatus === "Paid" ? "#fff" : s.paymentStatus === "Pending" ? "#7a4a00" : "var(--ink-3)",
                          }}>S{i+1}</span>
                        ))}
                      </div>
                    </td>
                  </>
                )}

                {role === "admin" && (
                  <td className="notes-cell" style={{ cursor: "pointer" }} onClick={(e) => { e.stopPropagation(); setNoteTarget(r); }}>
                    {r.note ? (
                      <>
                        <div className="note-preview">{r.note}</div>
                        <div className="note-tooltip">{r.note}</div>
                      </>
                    ) : <span className="text-xs text-mute add-note-hint">+ Add note</span>}
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <TablePagination page={pg} totalPages={totalPages} onPage={setPg} total={searchFiltered.length} perPage={perPage} />

      {noteTarget && <AddNoteModal
        influencer={noteTarget}
        notes={noteTarget.notes || []}
        onSave={(body) => {
          const at = new Date().toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) + ", " + new Date().toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
          const entry = { by: "Farah K. — Admin", at, body };
          const notes = [...(noteTarget.notes || []), entry];
          const actEntry = { at, what: "Note added by Admin", by: "Admin — Farah K." };
          updateInfluencer(noteTarget.id, { notes, note: body }, actEntry);
          notify("Note saved.");
          setNoteTarget(null);
        }}
        onClose={() => setNoteTarget(null)}
      />}
    </div>
  );
}

// ---------------- Stage bar (compact pipeline for table) ----------------

function StageBar({ stages, currentStage, stageState }) {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
      {stages.map((s) => (
        <div key={s.n} title={`Stage ${s.n}: ${s.state}`}
             style={{
               width: 22, height: 6, borderRadius: 2,
               background:
                 s.state === "Complete" ? "var(--ok)" :
                 s.state === "In Progress" ? "var(--ink)" :
                 "var(--line-2)",
             }} />
      ))}
      <span className="text-mono text-xs" style={{ marginLeft: 6, color: "var(--ink-3)" }}>
        {stageState === "Complete" ? "All Done" : `S${currentStage} · ${stageState}`}
      </span>
    </div>
  );
}

// ---------------- Inline KPI strip ----------------

function KpiInline({ data, variant }) {
  const kpis = useMemo(() => {
    const total = data.length;
    if (variant === "outreach") {
      let contacted = 0, accepted = 0, rejected = 0;
      data.forEach(r => {
        if (r.status === "Contacted")                         contacted++;
        if (r.status === "Accepted" || r.status === "Interested") accepted++;
        if (r.status === "Rejected")                          rejected++;
      });
      return [["Total", total], ["Contacted", contacted], ["Converted", accepted], ["Rejected", rejected]];
    } else {
      let stage4 = 0;
      data.forEach(r => { if (r.currentStage === 4) stage4++; });
      return [["Total", total], ["Active Stages", total], ["Stage 4", stage4], ["Blocked", 0]];
    }
  }, [data, variant]);

  return (
    <div style={{ display: "inline-flex", gap: 0, border: "1px solid var(--line)", borderRadius: 2 }}>
      {kpis.map(([l, v], i) => (
        <div key={i} style={{ padding: "6px 14px", borderRight: i < 3 ? "1px solid var(--line)" : "none" }}>
          <div className="text-mono text-xs text-mute" style={{ textTransform: "uppercase", letterSpacing: "0.1em" }}>{l}</div>
          <div className="text-mono" style={{ fontSize: 15, fontWeight: 500 }}>{v}</div>
        </div>
      ))}
    </div>
  );
}

// ---------------- Announcements chip (OS view only) ----------------

function AnnouncementsChip() {
  const { setPage, counts } = useApp();
  const n = counts.announcements || 0;
  if (n === 0) return null;
  return (
    <div className="announce">
      <span className="dot">Task</span>
      <span><strong>{n} {n === 1 ? "task" : "tasks"} pending.</strong> Upload the contact screenshot for {n === 1 ? "this influencer" : "these influencers"}.</span>
      <div style={{ flex: 1 }} />
      <button className="btn sm" onClick={() => setPage({ key: "announcements" })}>View <Ic.arrowRight /></button>
    </div>
  );
}

Object.assign(window, { InProgressPage, StageBar, KpiInline, AnnouncementsChip });
