"use client";

import { useState } from "react";
import { TrendingUp, ChevronDown } from "lucide-react";

interface Trend { title?: string; description?: string; impact?: string; relevance?: string; timeframe?: string }

const IMPACT_BORDER: Record<string, string> = { high: "border-l-red-500", medium: "border-l-amber-400", low: "border-l-blue-400" };
const TF_CLS: Record<string, string> = { immediate: "bg-red-50 text-red-700", "short-term": "bg-amber-50 text-amber-700", "long-term": "bg-blue-50 text-blue-700" };

interface Props { trends: Trend[] }

export default function MarketTrends({ trends }: Props) {
  const [showLow, setShowLow] = useState(false);
  if (!trends.length) return null;

  const high = trends.filter((t) => t.impact === "high");
  const medium = trends.filter((t) => t.impact === "medium");
  const low = trends.filter((t) => t.impact !== "high" && t.impact !== "medium");

  function renderCard(trend: Trend, i: number) {
    const border = IMPACT_BORDER[trend.impact || "low"] || IMPACT_BORDER.low;
    const tf = TF_CLS[trend.timeframe || ""] || TF_CLS["long-term"];
    return (
      <div key={i} className={`bg-white rounded-xl border border-slate-200 border-l-4 ${border} px-4 py-3`}>
        <div className="flex items-center gap-2 mb-1">
          <h3 className="text-sm font-bold text-slate-900">{trend.title}</h3>
          {trend.timeframe && <span className={`text-[9px] font-bold uppercase tracking-wider rounded-full px-2 py-0.5 ${tf}`}>{trend.timeframe}</span>}
        </div>
        {trend.description && <p className="text-xs text-slate-600 leading-relaxed mb-1">{trend.description}</p>}
        {trend.relevance && <p className="text-[11px] text-brand-700 font-medium">{trend.relevance}</p>}
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center gap-2 mb-3"><TrendingUp className="w-4 h-4 text-brand-600" /><h2 className="text-xs font-bold uppercase tracking-widest text-slate-400">Market Trends</h2></div>
      <div className="space-y-2">
        {high.map((t, i) => renderCard(t, i))}
        {medium.map((t, i) => renderCard(t, i + high.length))}
        {low.length > 0 && (
          <>
            <button onClick={() => setShowLow(!showLow)} className="flex items-center gap-1.5 text-xs font-semibold text-slate-500 hover:text-slate-700">
              <ChevronDown className={`w-3.5 h-3.5 transition-transform ${showLow ? "rotate-180" : ""}`} />
              {showLow ? "Hide" : "Show"} {low.length} low-impact trend{low.length !== 1 ? "s" : ""}
            </button>
            {showLow && low.map((t, i) => renderCard(t, i + high.length + medium.length))}
          </>
        )}
      </div>
    </div>
  );
}
