// HealthTrends — degradation/recovery/unstable tool trend indicators.

function HealthTrends({ tools, history }) {
  const [showDetails, setShowDetails] = useState(false);

  const metrics = React.useMemo(() => {
    const now = Date.now();
    const oneHourAgo = now - 3600000;
    const oneDayAgo = now - 86400000;

    const recentChecks = history.filter(h => h.timestamp > oneHourAgo);
    const dayChecks = history.filter(h => h.timestamp > oneDayAgo);

    const degradationPattern = [];
    const recoveryPattern = [];

    tools.forEach(tool => {
      const toolHistory = history.filter(h => h.tool === tool.name).slice(0, 10);
      if (toolHistory.length >= 3) {
        const statuses = toolHistory.map(h => h.status);
        const wasOk = statuses.slice(1).every(s => s === "ok");
        const nowDegraded = tool.status !== "ok";
        
        if (wasOk && nowDegraded) degradationPattern.push(tool.name);
        if (!wasOk && tool.status === "ok") recoveryPattern.push(tool.name);
      }
    });

    return {
      recentChecks: recentChecks.length,
      dayChecks: dayChecks.length,
      degradationPattern,
      recoveryPattern,
      unstableTools: tools.filter(t => 
        history.filter(h => h.tool === t.name && h.status !== "ok").length > 2
      ).map(t => t.name),
    };
  }, [tools, history]);

  if (metrics.degradationPattern.length === 0 && metrics.recoveryPattern.length === 0 && metrics.unstableTools.length === 0) {
    return null;
  }

  return (
    <div className="mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="text-amber-600">📊</span>
          <span className="text-sm font-medium text-amber-900">Health Trends</span>
        </div>
        <button onClick={() => setShowDetails(!showDetails)} className="text-xs text-amber-700 hover:underline">
          {showDetails ? "Hide" : "Details"}
        </button>
      </div>
      {showDetails && (
        <div className="mt-2 space-y-2 text-xs">
          {metrics.degradationPattern.length > 0 && (
            <div><span className="text-red-500">↓</span> <span className="font-medium">Recent degradation:</span> {metrics.degradationPattern.join(", ")}</div>
          )}
          {metrics.recoveryPattern.length > 0 && (
            <div><span className="text-emerald-500">↑</span> <span className="font-medium">Recovered:</span> {metrics.recoveryPattern.join(", ")}</div>
          )}
          {metrics.unstableTools.length > 0 && (
            <div><span className="text-amber-500">⚠</span> <span className="font-medium">Unstable tools:</span> {metrics.unstableTools.join(", ")}</div>
          )}
        </div>
      )}
    </div>
  );
}
