// List + table view, view toggle, filter dropdown, sort
const { useState: useStTbl, useRef: useRefTbl, useEffect: useEffTbl, useMemo: useMmTbl } = React;

function ViewToggle({ view, onChange }) {
  return (
    <div style={{
      display: "inline-flex", padding: 3,
      background: "#F3F3F1", borderRadius: 8,
      border: "1px solid #ECECEA",
    }}>
      {[
        { key: "list", label: "List", icon: Icons.list },
        { key: "kanban", label: "Kanban", icon: Icons.kanban },
      ].map(o => {
        const active = view === o.key;
        return (
          <button key={o.key} onClick={() => onChange(o.key)} style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "5px 11px", fontSize: 12, fontWeight: 500,
            border: "none", borderRadius: 6, cursor: "pointer",
            background: active ? "#fff" : "transparent",
            color: active ? "#1F2433" : "#6B7280",
            boxShadow: active ? "0 1px 2px rgba(15,20,35,0.06)" : "none",
            fontFamily: "inherit",
          }}>
            <o.icon size={13} /> {o.label}
          </button>
        );
      })}
    </div>
  );
}

function FilterPanel({ filters, setFilters, stages, agents, onClose }) {
  const ref = useRefTbl(null);
  useEffTbl(() => {
    const h = (e) => { if (!ref.current?.contains(e.target)) onClose(); };
    setTimeout(() => window.addEventListener("mousedown", h), 0);
    return () => window.removeEventListener("mousedown", h);
  }, []);
  const toggleSet = (key, val) => {
    const set = new Set(filters[key]);
    set.has(val) ? set.delete(val) : set.add(val);
    setFilters({ ...filters, [key]: [...set] });
  };
  return (
    <div ref={ref} style={{
      position: "absolute", top: "calc(100% + 8px)", left: 0, zIndex: 60,
      width: 340, padding: 16,
      background: "#fff", border: "1px solid #ECECEA", borderRadius: 12,
      boxShadow: "0 12px 36px rgba(15,20,35,0.10)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <span style={{ fontSize: 13, fontWeight: 500, color: "#1F2433" }}>Filters</span>
        <button onClick={() => setFilters({ stages: [], agents: [], min: 1000000, max: 7000000, days: 30 })}
          style={{ background: "none", border: "none", fontSize: 11.5, color: "#5684CC", cursor: "pointer", fontFamily: "inherit" }}>
          Reset all
        </button>
      </div>

      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 10.5, color: "#6B7280", letterSpacing: 0.5, textTransform: "uppercase", marginBottom: 6 }}>Stage</div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {stages.map(s => {
            const on = filters.stages.includes(s.id);
            return (
              <span key={s.id} onClick={() => toggleSet("stages", s.id)} style={{
                display: "inline-flex", alignItems: "center", gap: 5,
                padding: "4px 9px", borderRadius: 999, cursor: "pointer",
                fontSize: 11.5, fontWeight: 500,
                background: on ? s.bg : "#fff",
                color: on ? s.fg : "#6B7280",
                border: "1px solid " + (on ? s.fg + "33" : "#ECECEA"),
              }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: s.color }} />
                {s.label}
              </span>
            );
          })}
        </div>
      </div>

      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 10.5, color: "#6B7280", letterSpacing: 0.5, textTransform: "uppercase", marginBottom: 6 }}>FOS Agent</div>
        <div style={{ display: "flex", gap: 6 }}>
          {Object.entries(agents).map(([id, a]) => {
            const on = filters.agents.includes(id);
            return (
              <span key={id} onClick={() => toggleSet("agents", id)} style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                padding: "4px 9px 4px 4px", borderRadius: 999, cursor: "pointer",
                fontSize: 11.5, fontWeight: 500,
                background: on ? "#EFF7E8" : "#fff",
                color: on ? "#1F2433" : "#6B7280",
                border: "1px solid " + (on ? "#A3E494" : "#ECECEA"),
              }}>
                <Avatar initials={a.initials} color={a.color} size={18} />
                {a.name}
              </span>
            );
          })}
        </div>
      </div>

      <div style={{ marginBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
          <span style={{ fontSize: 10.5, color: "#6B7280", letterSpacing: 0.5, textTransform: "uppercase" }}>Loan Amount</span>
          <span style={{ fontSize: 11, color: "#1F2433", fontVariantNumeric: "tabular-nums" }}>
            {formatINR(filters.min)} – {formatINR(filters.max)}
          </span>
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <input type="range" min={500000} max={10000000} step={500000} value={filters.min}
            onChange={(e) => setFilters({ ...filters, min: +e.target.value })}
            style={{ flex: 1, accentColor: "#A3E494" }} />
          <input type="range" min={500000} max={10000000} step={500000} value={filters.max}
            onChange={(e) => setFilters({ ...filters, max: +e.target.value })}
            style={{ flex: 1, accentColor: "#A3E494" }} />
        </div>
      </div>

      <div>
        <div style={{ fontSize: 10.5, color: "#6B7280", letterSpacing: 0.5, textTransform: "uppercase", marginBottom: 6 }}>Last Activity</div>
        <div style={{ display: "flex", gap: 6 }}>
          {[
            { v: 1, l: "24h" }, { v: 7, l: "7 days" }, { v: 30, l: "30 days" }, { v: 90, l: "All time" },
          ].map(o => (
            <span key={o.v} onClick={() => setFilters({ ...filters, days: o.v })} style={{
              padding: "5px 11px", borderRadius: 6, cursor: "pointer",
              fontSize: 11.5, fontWeight: 500,
              background: filters.days === o.v ? "#1F2433" : "#fff",
              color: filters.days === o.v ? "#fff" : "#6B7280",
              border: "1px solid " + (filters.days === o.v ? "#1F2433" : "#ECECEA"),
            }}>{o.l}</span>
          ))}
        </div>
      </div>
    </div>
  );
}

function SortMenu({ sort, setSort, onClose }) {
  const ref = useRefTbl(null);
  useEffTbl(() => {
    const h = (e) => { if (!ref.current?.contains(e.target)) onClose(); };
    setTimeout(() => window.addEventListener("mousedown", h), 0);
    return () => window.removeEventListener("mousedown", h);
  }, []);
  const opts = [
    { key: "lastActivity", label: "Most recent activity" },
    { key: "amount-desc",  label: "Loan ask (high → low)" },
    { key: "amount-asc",   label: "Loan ask (low → high)" },
    { key: "borrower",     label: "Borrower name (A → Z)" },
    { key: "stage",        label: "Stage" },
  ];
  return (
    <div ref={ref} style={{
      position: "absolute", top: "calc(100% + 8px)", left: 0, zIndex: 60,
      minWidth: 240, padding: 6,
      background: "#fff", border: "1px solid #ECECEA", borderRadius: 10,
      boxShadow: "0 12px 36px rgba(15,20,35,0.10)",
    }}>
      {opts.map(o => (
        <div key={o.key} onClick={() => { setSort(o.key); onClose(); }} style={{
          padding: "8px 10px", borderRadius: 6, cursor: "pointer",
          fontSize: 12.5, color: "#1F2433",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          background: sort === o.key ? "#F6FAF1" : "transparent",
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = "#F6FAF1"}
        onMouseLeave={(e) => e.currentTarget.style.background = sort === o.key ? "#F6FAF1" : "transparent"}
        >
          <span>{o.label}</span>
          {sort === o.key && <Icons.check size={13} style={{ color: "#6BAE5B" }} />}
        </div>
      ))}
    </div>
  );
}

function TableToolbar({ filters, setFilters, stages, agents, sort, setSort, view, setView, totalCount, shownCount }) {
  const [filterOpen, setFilterOpen] = useStTbl(false);
  const [sortOpen, setSortOpen] = useStTbl(false);
  const activeFilters =
    filters.stages.length + filters.agents.length +
    (filters.min > 1000000 || filters.max < 7000000 ? 1 : 0) +
    (filters.days < 30 ? 1 : 0);
  return (
    <div style={{
      padding: "12px 18px",
      display: "flex", alignItems: "center", justifyContent: "space-between",
      borderBottom: "1px solid #ECECEA", background: "#FCFCFB",
    }}>
      <div style={{ display: "flex", gap: 8, alignItems: "center", position: "relative" }}>
        <div style={{ position: "relative" }}>
          <button onClick={() => { setFilterOpen(o => !o); setSortOpen(false); }} style={{
            ...toolbarBtn,
            borderColor: filterOpen ? "#1F2433" : "#ECECEA",
          }}>
            <Icons.filter size={13} /> Filter
            {activeFilters > 0 && (
              <span style={{ background: "#A3E494", color: "#1F2433", fontSize: 10, fontWeight: 600, padding: "1px 6px", borderRadius: 999 }}>
                {activeFilters}
              </span>
            )}
          </button>
          {filterOpen && <FilterPanel filters={filters} setFilters={setFilters} stages={stages} agents={agents} onClose={() => setFilterOpen(false)} />}
        </div>
        <div style={{ position: "relative" }}>
          <button onClick={() => { setSortOpen(o => !o); setFilterOpen(false); }} style={{
            ...toolbarBtn,
            borderColor: sortOpen ? "#1F2433" : "#ECECEA",
          }}>
            <Icons.sort size={13} /> Sort
          </button>
          {sortOpen && <SortMenu sort={sort} setSort={setSort} onClose={() => setSortOpen(false)} />}
        </div>
        <div style={{ height: 18, width: 1, background: "#ECECEA", margin: "0 4px" }} />
        <div style={{ display: "flex", gap: 6 }}>
          <span style={pillActive}>My pipeline</span>
          <span style={pill}>Active only</span>
        </div>
      </div>
      <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
        <span style={{ fontSize: 11.5, color: "#6B7280", whiteSpace: "nowrap" }}>
          Showing <strong style={{ color: "#1F2433", fontWeight: 500 }}>{shownCount}</strong> of {totalCount} leads
        </span>
        <ViewToggle view={view} onChange={setView} />
      </div>
    </div>
  );
}

const toolbarBtn = {
  display: "inline-flex", alignItems: "center", gap: 6,
  padding: "6px 11px",
  background: "#fff", border: "1px solid #ECECEA", borderRadius: 7,
  fontSize: 12, fontWeight: 500, color: "#1F2433",
  cursor: "pointer", fontFamily: "inherit",
};
const pill = {
  padding: "5px 10px", borderRadius: 999,
  background: "#fff", border: "1px solid #ECECEA",
  fontSize: 11.5, color: "#6B7280",
};
const pillActive = {
  padding: "5px 10px", borderRadius: 999,
  background: "#EFF7E8", border: "1px solid #C7E5B3",
  fontSize: 11.5, color: "#3F7A33", fontWeight: 500,
};

function ListView({ leads, agents, stages, sort, onOpen, onUpdateLead }) {
  const sorted = useMmTbl(() => {
    const ls = [...leads];
    const stageOrder = ["new","progress","assessment","meeting","won"];
    const cmp = {
      "lastActivity": (a,b) => activityRank(a.lastActivity) - activityRank(b.lastActivity),
      "amount-desc":  (a,b) => b.amount - a.amount,
      "amount-asc":   (a,b) => a.amount - b.amount,
      "borrower":     (a,b) => a.borrower.localeCompare(b.borrower),
      "stage":        (a,b) => stageOrder.indexOf(a.stageId) - stageOrder.indexOf(b.stageId),
    }[sort] || ((a,b) => 0);
    ls.sort(cmp);
    // pinned always on top
    ls.sort((a,b) => (b.pinned?1:0) - (a.pinned?1:0));
    return ls;
  }, [leads, sort]);

  const showAgent = false; // Always Vikram's view
  const cols = "minmax(240px,2fr) 1.4fr 1.1fr 1.3fr 1.2fr 0.7fr 0.4fr";

  return (
    <div>
      <div style={{
        display: "grid", gridTemplateColumns: cols,
        padding: "10px 18px",
        fontSize: 10.5, fontWeight: 500, color: "#9CA3AF",
        letterSpacing: 0.6, textTransform: "uppercase",
        borderBottom: "1px solid #ECECEA",
        background: "#FCFCFB",
        gap: 12,
      }}>
        <span>Borrower</span>
        <span>Business Type</span>
        <span style={{ textAlign: "right" }}>Loan ask</span>
        <span>Stage</span>
        <span>Last activity</span>
        <span style={{ textAlign: "center" }}>Action</span>
        <span></span>
      </div>
      {sorted.map((lead, idx) => (
        <LeadRow key={lead.id} lead={lead} idx={idx} cols={cols} showAgent={false}
          agents={agents} stages={stages}
          onClick={() => onOpen(lead.id)}
          onUpdate={(patch) => onUpdateLead(lead.id, patch)} />
      ))}
      {sorted.length === 0 && (
        <div style={{ padding: 60, textAlign: "center", color: "#9CA3AF", fontSize: 13 }}>
          No leads match the current filters.
        </div>
      )}
    </div>
  );
}

function activityRank(s) {
  if (!s) return 99;
  if (s.toLowerCase().includes("just")) return 0;
  const m = s.match(/(\d+)\s*([hd])/);
  if (!m) return 99;
  return (m[2] === "d" ? 24 : 1) * +m[1];
}

function LeadRow({ lead, idx, cols, showAgent, agents, stages, onClick, onUpdate }) {
  const agent = agents[lead.agentId];
  const initials = lead.borrower.split(" ").map(w => w[0]).slice(0,2).join("");
  const borrowerColor = ["#5684CC","#A78BC7","#4FA8A5","#6BAE5B","#D49A3A"][lead.id % 5];

  return (
    <div
      onClick={onClick}
      style={{
        display: "grid", gridTemplateColumns: cols, gap: 12,
        padding: "13px 18px",
        borderBottom: "1px solid #F2F2F0",
        alignItems: "center",
        cursor: "pointer",
        background: lead.pinned ? "#FCFEFA" : "#fff",
        transition: "background 120ms ease",
        position: "relative",
      }}
      onMouseEnter={(e) => e.currentTarget.style.background = "#F6FAF1"}
      onMouseLeave={(e) => e.currentTarget.style.background = lead.pinned ? "#FCFEFA" : "#fff"}
    >
      {lead.pinned && (
        <span style={{
          position: "absolute", left: 0, top: 0, bottom: 0, width: 2,
          background: "#A3E494",
        }} />
      )}
      <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
        <Avatar initials={initials} color={borrowerColor} size={32} />
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ fontSize: 13, fontWeight: 500, color: "#1F2433" }}>
              <EditableText value={lead.borrower} onChange={(v) => onUpdate({ borrower: v })} />
            </span>
            {lead.pinned && (
              <span title="Pinned" style={{ display: "inline-flex", alignItems: "center", color: "#6BAE5B" }}>
                <Icons.pin size={11} />
              </span>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: "#6B7280", marginTop: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            <EditableText value={lead.business} onChange={(v) => onUpdate({ business: v })} />
          </div>
        </div>
      </div>

      <div style={{ fontSize: 12.5, color: "#1F2433" }}>
        <EditableText value={lead.sector} onChange={(v) => onUpdate({ sector: v })} />
      </div>

      <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1F2433", textAlign: "right", fontVariantNumeric: "tabular-nums" }}>
        {formatINR(lead.amount)}
      </div>

      {showAgent && (
        <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
          <Avatar initials={agent.initials} color={agent.color} size={22} />
          <span style={{ fontSize: 12.5, color: "#1F2433" }}>{agent.name}</span>
        </div>
      )}

      <div onClick={(e) => e.stopPropagation()}>
        <StageBadge stageId={lead.stageId} stages={stages} onChange={(id) => onUpdate({ stageId: id })} />
      </div>

      <div style={{ fontSize: 12, color: "#6B7280" }}>{lead.lastActivity}</div>

      <div style={{ textAlign: "center" }}>
        {lead.awaiting ? (
          <span className="pulseDot" style={{
            display: "inline-block", width: 9, height: 9, borderRadius: 999,
            background: "#D49A3A",
          }} title="Action pending" />
        ) : (
          <span style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            width: 18, height: 18, borderRadius: 999, background: "#EDF6E8",
          }} title="No action needed">
            <Icons.check size={11} style={{ color: "#3F7A33" }} />
          </span>
        )}
      </div>

      <div style={{ textAlign: "right" }} onClick={(e) => e.stopPropagation()}>
        <button style={{
          background: "transparent", border: "none", cursor: "pointer",
          color: "#9CA3AF", padding: 4, borderRadius: 4,
        }}><Icons.dots size={16} /></button>
      </div>
    </div>
  );
}

Object.assign(window, { TableToolbar, ListView, ViewToggle });
