// Global changes feed

function ChangesFeed({ onOpenAccount }) {
  const data = window.FABCOM_DATA;
  const [dateRange, setDateRange] = useState("7d");
  const [account, setAccount] = useState("");
  const [actor, setActor] = useState("");
  const [eventType, setEventType] = useState("");
  const [query, setQuery] = useState("");

  const actors = [...new Set(data.history.map(h => h.actor))].sort();
  const events = [...new Set(data.history.map(h => h.event_type))];
  const days = dateRange === "24h" ? 1 : dateRange === "7d" ? 7 : dateRange === "14d" ? 14 : 30;
  const cutoff = Date.now() - days*86400e3;

  const filtered = data.history.filter(h => {
    if (h.ts < cutoff) return false;
    if (account && h.account_id !== account) return false;
    if (actor && h.actor !== actor) return false;
    if (eventType && h.event_type !== eventType) return false;
    if (query) {
      const q = query.toLowerCase();
      if (!(h.entity_name.toLowerCase().includes(q) || String(h.new_value).toLowerCase().includes(q) || String(h.old_value).toLowerCase().includes(q))) return false;
    }
    return true;
  });

  const byAccount = useMemo(() => Object.fromEntries(data.accounts.map(a => [a.id, a])), []);

  return (
    <div className="h-full flex flex-col gap-3">
      <div>
        <div className="text-3 text-[12px] mb-1">Audit · all entities</div>
        <h1 className="text-[22px] font-semibold tracking-tight">Changes feed</h1>
        <div className="text-3 text-[12px] mt-1">Every setting change across 142 accounts. Sourced from <span className="mono">campaigns_history</span>, <span className="mono">adsets_history</span>, <span className="mono">ads_history</span>.</div>
      </div>

      <div className="surface rounded-xl p-3 flex items-center gap-2 flex-wrap">
        <SearchInput value={query} onChange={setQuery} placeholder="Search entity, value…" className="w-[240px]"/>
        <Select value={dateRange} onChange={setDateRange} options={[
          {value:"24h", label:"Last 24h"},{value:"7d",label:"Last 7 days"},{value:"14d",label:"Last 14 days"},{value:"30d",label:"Last 30 days"},
        ]}/>
        <Select value={account} onChange={setAccount}
          options={[{value:"",label:"All accounts"},...data.accounts.map(a => ({value:a.id,label:a.name}))]}/>
        <Select value={actor} onChange={setActor}
          options={[{value:"",label:"All actors"},...actors.map(a => ({value:a,label:a}))]}/>
        <Select value={eventType} onChange={setEventType}
          options={[{value:"",label:"All event types"},...events.map(e => ({value:e,label:e}))]}/>
        <div className="flex-1"/>
        <div className="text-3 text-[11.5px] mono tnum">{filtered.length.toLocaleString()} events</div>
        <Button icon="sheet">Export</Button>
        <Button icon="link">Copy URL</Button>
      </div>

      <div className="surface rounded-xl flex-1 overflow-hidden flex flex-col">
        <div className="overflow-auto">
          <table className="w-full sticky-head">
            <thead>
              <tr>
                <th className="text-left">When</th>
                <th className="text-left">Account</th>
                <th className="text-left">Entity</th>
                <th className="text-left">Actor</th>
                <th className="text-left">Event</th>
                <th className="text-left">Field</th>
                <th className="text-left">Before → After</th>
              </tr>
            </thead>
            <tbody>
              {filtered.slice(0, 200).map(h => {
                const acc = byAccount[h.account_id];
                return (
                  <tr key={h.id} className="row">
                    <td className="tnum"><div>{window.timeAgo(h.ts)}</div><div className="text-3 text-[11px]">{window.formatFullTs(h.ts)}</div></td>
                    <td>
                      <button onClick={() => onOpenAccount(h.account_id)} className="text-1 hover:accent-text">{acc?.name}</button>
                      <div className="mono text-3 text-[11px]">{h.account_id}</div>
                    </td>
                    <td>
                      <div className="flex items-center gap-1.5">
                        <Chip>{h.entity_kind}</Chip>
                        <span className="text-2 text-[12px] truncate max-w-[220px]">{h.entity_name}</span>
                      </div>
                      <div className="mono text-3 text-[11px]">{h.entity_id}</div>
                    </td>
                    <td className="text-2">{h.actor}</td>
                    <td><Chip tone={h.event_type==="budget_change"?"amber":h.event_type==="status_change"?"default":"accent"}>{h.event_type}</Chip></td>
                    <td className="mono text-2 text-[11.5px]">{h.field}</td>
                    <td><Diff oldV={h.old_value} newV={h.new_value} money={h.field.includes("budget")} ccy={acc?.ccy || "HKD"}/></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filtered.length > 200 && (
          <div className="border-t border-soft px-3 py-2 text-3 text-[11.5px]">Showing first 200 events. Refine filters to see more.</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ChangesFeed });
