// components/logs.jsx — LogPanel with extracted useLogFilter hook.
// Depends on: React (useState, useMemo)

const LOG_COLORS = {
  ERROR: "bg-red-100 text-red-700 border-red-200",
  WARN: "bg-amber-100 text-amber-700 border-amber-200",
  INFO: "bg-blue-100 text-blue-700 border-blue-200",
  DEBUG: "bg-gray-100 text-gray-600 border-gray-200",
};

// ── Hook: useLogFilter ──────────────────────────────────────
function useLogFilter(logs) {
  const [filter, setFilter] = useState("ALL");

  const filtered = React.useMemo(() =>
    (filter === "ALL" ? logs : logs?.filter(l => l.level === filter)) || [],
    [logs, filter]
  );

  const errorCount = React.useMemo(() => logs?.filter(l => l.level === "ERROR").length || 0, [logs]);
  const warnCount = React.useMemo(() => logs?.filter(l => l.level === "WARN").length || 0, [logs]);

  return { filtered, filter, setFilter, errorCount, warnCount };
}

// ── LogRow ──────────────────────────────────────────────────
function LogRow({ entry }) {
  return (
    <div className={`flex items-start gap-2 text-xs p-1.5 rounded border ${LOG_COLORS[entry.level] || LOG_COLORS.INFO}`}>
      <span className="font-mono opacity-60 whitespace-nowrap">{entry.timestamp}</span>
      <span className="font-bold whitespace-nowrap">{entry.level}</span>
      <span className="break-all">{entry.message}</span>
    </div>
  );
}

// ── LogPanel (refactored: CC ≤ 5) ──────────────────────────
function LogPanel({ logs, error, source }) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [copyStatus, setCopyStatus] = useState(null);
  const { filtered, filter, setFilter, errorCount, warnCount } = useLogFilter(logs);

  const handleCopy = async () => {
    const text = (filtered || [])
      .map(e => `${e.timestamp || ""}\t${e.level || ""}\t${e.message || ""}`.trim())
      .join("\n");

    try {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
      } else {
        const ta = document.createElement("textarea");
        ta.value = text;
        ta.style.position = "fixed";
        ta.style.left = "-9999px";
        document.body.appendChild(ta);
        ta.focus();
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
      }
      setCopyStatus("copied");
    } catch (e) {
      setCopyStatus("error");
    }

    setTimeout(() => setCopyStatus(null), 1200);
  };

  return (
    <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-50">
      {/* Header bar */}
      <div className="flex items-center justify-between px-4 py-2 bg-gray-50 border-b border-gray-200">
        <div className="flex items-center gap-3">
          <button 
            onClick={() => setIsExpanded(!isExpanded)}
            className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-gray-900"
          >
            <span>{isExpanded ? "▼" : "▲"}</span>
            Logs {source && `(${source.split('/').pop()})`}
          </button>
          
          {/* Level filters */}
          <div className="flex items-center gap-1 text-xs">
            <button 
              onClick={() => setFilter("ALL")}
              className={`px-2 py-0.5 rounded ${filter === "ALL" ? "bg-gray-800 text-white" : "bg-gray-200 text-gray-600"}`}
            >
              ALL
            </button>
            <button 
              onClick={() => setFilter("ERROR")}
              className={`px-2 py-0.5 rounded ${filter === "ERROR" ? "bg-red-600 text-white" : errorCount > 0 ? "bg-red-100 text-red-600" : "bg-gray-200 text-gray-600"}`}
            >
              ERR {errorCount > 0 && `(${errorCount})`}
            </button>
            <button 
              onClick={() => setFilter("WARN")}
              className={`px-2 py-0.5 rounded ${filter === "WARN" ? "bg-amber-600 text-white" : warnCount > 0 ? "bg-amber-100 text-amber-600" : "bg-gray-200 text-gray-600"}`}
            >
              WARN {warnCount > 0 && `(${warnCount})`}
            </button>
            <button 
              onClick={() => setFilter("INFO")}
              className={`px-2 py-0.5 rounded ${filter === "INFO" ? "bg-blue-600 text-white" : "bg-gray-200 text-gray-600"}`}
            >
              INFO
            </button>
          </div>
        </div>
        
        <div className="flex items-center gap-3">
          <button
            onClick={handleCopy}
            className="text-xs px-2 py-1 border rounded bg-white hover:bg-gray-50"
            disabled={!filtered || filtered.length === 0}
            title={filtered?.length ? `Copy ${filtered.length} log lines` : "No logs to copy"}
          >
            Copy
          </button>
          {copyStatus === "copied" && <span className="text-xs text-emerald-700">Copied</span>}
          {copyStatus === "error" && <span className="text-xs text-red-600">Copy failed</span>}
          {error && (
            <span className="text-xs text-red-600">{error}</span>
          )}
        </div>
      </div>
      
      {/* Log content */}
      {isExpanded && (
        <div className="max-h-64 overflow-y-auto px-4 py-2 space-y-1">
          {filtered.length === 0 ? (
            <p className="text-xs text-gray-400 italic">No logs to display</p>
          ) : (
            filtered.map((entry, i) => <LogRow key={i} entry={entry} />)
          )}
        </div>
      )}
      
      {/* Mini preview when collapsed */}
      {!isExpanded && logs?.length > 0 && (
        <div className="px-4 py-1 flex items-center gap-2 text-xs">
          {errorCount > 0 && (
            <span className="text-red-600 font-medium">⚠ {errorCount} errors</span>
          )}
          {warnCount > 0 && (
            <span className="text-amber-600 font-medium">⚡ {warnCount} warnings</span>
          )}
          <span className="text-gray-400">{logs.length} total entries</span>
          <span className="text-gray-300">|</span>
          <span className="text-gray-500 italic">
            {logs[logs.length - 1]?.message?.substring(0, 80)}...
          </span>
        </div>
      )}
    </div>
  );
}
