"use client";

import { useState, useRef, useEffect, useCallback, useMemo } from "react";
import {
  Hash,
  Flame,
  Zap,
  Users,
  FileText,
  Wrench,
  Heart,
  X,
  SkipForward,
  MessageSquare,
} from "lucide-react";
import { WorkflowOps, CredentialRequirement, ThreadMessage } from "@/lib/types";
import { useChat } from "@/hooks/useChat";
import { useThreadManager } from "@/hooks/useThreadChat";
import { getChannel } from "@/lib/channels";
import { getAppDisplayName } from "@/lib/appNames";
import { getAppIntake } from "@/lib/app-intakes";
import { generateId } from "@/lib/utils";
import { MessageList } from "./MessageList";
import { ChatInput } from "./ChatInput";
import { McpAppToolbar } from "@/components/mcp/McpAppToolbar";
import { McpAppCard } from "@/components/mcp/McpAppCard";
import { CredentialConnector } from "@/components/workflow/CredentialConnector";

interface ChatViewProps {
  channelId: string;
}

const channelIcons: Record<string, React.ReactNode> = {
  general: <Hash className="w-5 h-5" />,
  automations: <Zap className="w-5 h-5" />,
  crm: <Users className="w-5 h-5" />,
  templates: <FileText className="w-5 h-5" />,
  nodes: <Wrench className="w-5 h-5" />,
  health: <Heart className="w-5 h-5" />,
};

export function ChatView({ channelId }: ChatViewProps) {
  const channel = getChannel(channelId);
  const { messages, isLoading, sendMessage, addMessage, removeMessage } = useChat({
    channelId,
  });

  // ─── Thread manager ──────────────────────────────────────────────────────
  const threadManager = useThreadManager(channelId);

  // Derive activeAppIds from open panels in the current channel
  const activeAppIds = useMemo(() => {
    return new Set(
      threadManager.openPanelThreads
        .filter(({ channelId: c }) => c === channelId)
        .map(({ thread }) => thread.appId)
    );
  }, [threadManager.openPanelThreads, channelId]);

  // ─── Auto-open default app thread when entering a channel ──────────────
  const autoOpenedRef = useRef<string | null>(null);

  useEffect(() => {
    if (!channel?.defaultApp) {
      autoOpenedRef.current = null;
      return;
    }

    // Only auto-open once per channel visit
    if (autoOpenedRef.current === channelId) return;
    autoOpenedRef.current = channelId;

    const appId = channel.defaultApp;
    const existingThread = threadManager.findThreadByAppId(appId);

    if (existingThread) {
      // Reopen existing thread
      threadManager.openThread(existingThread.threadId);
    } else {
      // Create new thread for the default app
      const displayName = getAppDisplayName(appId);
      const intake = getAppIntake(appId);
      const parentId = generateId();
      const threadId = threadManager.createThread(
        appId,
        intake?.category || "general",
        parentId
      );

      // Add intake question to main chat as thread anchor
      addMessage({
        id: parentId,
        role: "assistant",
        content: intake?.question || "What would you like to do?",
        timestamp: new Date(),
        threadId,
        threadAppId: appId,
        threadTitle: displayName.name,
        threadIcon: displayName.icon,
        skipLabel: intake?.skipLabel,
      });

      // Skip to show app immediately at top of thread
      threadManager.skipThread(threadId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channelId]);

  // Refs for workflow ops → iframe postMessage
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const sentWorkflowOpsRef = useRef<Set<string>>(new Set());

  // Track latest credential requirements
  const [activeCredentials, setActiveCredentials] = useState<
    CredentialRequirement[]
  >([]);

  // ─── Reset credentials when channel changes ──────────────────────────
  const prevChannelIdRef = useRef(channelId);
  if (prevChannelIdRef.current !== channelId) {
    prevChannelIdRef.current = channelId;
    setActiveCredentials([]);
  }

  // When a message contains workflowOps (from main chat in automations channel),
  // POST to workflow-ops API so the builder iframe picks them up
  useEffect(() => {
    const lastMsg = messages[messages.length - 1];
    if (lastMsg?.workflowOps && !sentWorkflowOpsRef.current.has(lastMsg.id)) {
      sentWorkflowOpsRef.current.add(lastMsg.id);
      const ops = lastMsg.workflowOps;

      // POST ops to the API endpoint — the iframe polls this
      fetch("/api/workflow-ops", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(ops),
      }).catch(() => {});

      // Show credential connector if credentials are required
      if (ops.requiredCredentials && ops.requiredCredentials.length > 0) {
        setActiveCredentials(ops.requiredCredentials);
      } else {
        setActiveCredentials([]);
      }
    }
  }, [messages]);

  // ─── Handle app selection from toolbar ─────────────────────────────────

  const handleSelectApp = useCallback(
    (appId: string | null) => {
      if (!appId) {
        // Close all panels for current channel
        threadManager.openPanelThreads
          .filter(({ channelId: c }) => c === channelId)
          .forEach(({ thread }) => {
            threadManager.closePanel(channelId, thread.threadId);
          });
        setActiveCredentials([]);
        return;
      }

      // If clicking an active app, close its panel (toggle off)
      const existingThread = threadManager.findThreadByAppId(appId);
      if (existingThread && activeAppIds.has(appId)) {
        threadManager.closePanel(channelId, existingThread.threadId);
        setActiveCredentials([]);
        return;
      }

      // Check capacity
      if (!threadManager.canOpenMore) {
        // At capacity — could show a toast, for now just return
        return;
      }

      // All apps use thread mode now
      const intake = getAppIntake(appId);

      if (!intake) {
        return;
      }

      // Check if there's already a thread for this app
      if (existingThread) {
        // Reopen existing thread panel
        threadManager.openThread(existingThread.threadId);
        return;
      }

      // Thread mode: create intake question in main chat + open thread panel
      const displayName = getAppDisplayName(appId);
      const parentId = generateId();
      const threadId = threadManager.createThread(
        appId,
        intake.category,
        parentId
      );

      // Add the intake question as a message in the main chat
      addMessage({
        id: parentId,
        role: "assistant",
        content: intake.question,
        timestamp: new Date(),
        threadId,
        threadAppId: appId,
        threadTitle: displayName.name,
        threadIcon: displayName.icon,
        skipLabel: intake.skipLabel,
      });
    },
    [activeAppIds, threadManager, addMessage, channelId]
  );

  // ─── Handle opening a thread from clicking indicator ───────────────────

  const handleOpenThread = useCallback(
    (threadId: string) => {
      const thread = threadManager.getThread(threadId);
      if (thread) {
        if (!threadManager.canOpenMore) {
          // Check if it's already open
          const alreadyOpen = threadManager.openPanels.some(
            (p) => p.channelId === channelId && p.threadId === threadId
          );
          if (!alreadyOpen) return; // at capacity
        }
        threadManager.openThread(threadId);
      }
    },
    [threadManager, channelId]
  );

  // ─── Handle skip button ───────────────────────────────────────────────

  const handleSkip = useCallback(
    (threadId: string) => {
      const thread = threadManager.getThread(threadId);
      if (thread) {
        threadManager.skipThread(threadId);
      }
    },
    [threadManager]
  );

  // ─── Handle deleting a thread (X button) ──────────────────────────────

  const handleDeleteThread = useCallback(
    (threadId: string, parentMessageId: string) => {
      // Destroy thread state + localStorage + remove from panels
      threadManager.destroyThread(threadId);
      // Remove the parent message from the main chat
      removeMessage(parentMessageId);
    },
    [threadManager, removeMessage]
  );

  if (!channel) return null;

  const showWelcome =
    messages.length === 0 && threadManager.openPanelThreads.length === 0;
  const hasMcpApps = channel.mcpApps && channel.mcpApps.length > 0;

  // Determine which thread is active for MessageList highlighting
  // (use first open panel in current channel, or null)
  const activeThreadInChannel = threadManager.openPanelThreads.find(
    ({ channelId: c }) => c === channelId
  );
  const activeThreadId = activeThreadInChannel?.thread.threadId ?? null;

  return (
    <div className="flex flex-col h-full min-h-0">
      {/* ═══ Channel header ═══ */}
      <div
        className="h-12 flex items-center px-4 gap-2 shrink-0 shadow-sm"
        style={{
          borderBottom: "1px solid rgba(0,0,0,0.3)",
          backgroundColor: "#23272e",
        }}
      >
        <div style={{ color: "#72767d" }}>
          {channelIcons[channelId] || <Hash className="w-5 h-5" />}
        </div>
        <span
          className="text-[15px] font-semibold"
          style={{ color: "#ffffff" }}
        >
          {channel.name}
        </span>
        <div
          className="w-[1px] h-6 mx-2"
          style={{ backgroundColor: "#2f3136" }}
        />
        <span className="text-sm truncate" style={{ color: "#72767d" }}>
          {channel.description}
        </span>
      </div>

      {/* ═══ MCP App Toolbar ═══ */}
      {hasMcpApps && (
        <McpAppToolbar
          appIds={channel.mcpApps!}
          activeAppIds={activeAppIds}
          onSelectApp={handleSelectApp}
        />
      )}

      {/* ═══ Main content: Chat + optional Thread Panels ═══ */}
      <div className="flex flex-1 min-h-0 overflow-hidden">
        {/* ─── Main chat column ─── */}
        <div className="flex-1 flex flex-col min-w-0 min-h-0">
          {/* Credential Connector */}
          {activeCredentials.length > 0 && (
            <CredentialConnector credentials={activeCredentials} />
          )}

          {/* Messages or Welcome */}
          {showWelcome ? (
            <div className="flex-1 flex items-center justify-center min-h-0 overflow-y-auto">
              <WelcomeScreen
                channelId={channelId}
                channelName={channel.name}
              />
            </div>
          ) : (
            <MessageList
              messages={messages}
              isLoading={isLoading}
              threads={threadManager.threads}
              activeThreadId={activeThreadId}
              onOpenThread={handleOpenThread}
              onSkipThread={handleSkip}
              onDeleteThread={handleDeleteThread}
            />
          )}

          {/* Main chat input */}
          <ChatInput
            onSend={sendMessage}
            disabled={isLoading}
            channelName={channel.name}
          />
        </div>

        {/* ─── Multi-panel thread container ─── */}
        {threadManager.openPanelThreads.length > 0 && (
          <div
            className="flex shrink-0 overflow-hidden"
            style={{ maxWidth: "80%" }}
          >
            {threadManager.openPanelThreads.map(
              ({ channelId: panelChannelId, thread }) => {
                const appDisplay = getAppDisplayName(thread.appId);
                const panelChannel = getChannel(panelChannelId);
                const isCrossChannel = panelChannelId !== channelId;

                return (
                  <ThreadPanel
                    key={`${panelChannelId}-${thread.threadId}`}
                    thread={thread}
                    appDisplay={appDisplay}
                    appId={thread.appId}
                    channelName={
                      isCrossChannel ? panelChannel?.name : undefined
                    }
                    showApp={thread.appData !== null || thread.skipped}
                    iframeRef={
                      thread.appId === "n8n-workflow-builder"
                        ? iframeRef
                        : undefined
                    }
                    onClose={() =>
                      threadManager.closePanel(
                        panelChannelId,
                        thread.threadId
                      )
                    }
                    onDelete={() => {
                      threadManager.destroyThread(thread.threadId);
                      if (panelChannelId === channelId) {
                        removeMessage(thread.parentMessageId);
                      }
                    }}
                    onSend={(content) =>
                      threadManager.sendMessage(
                        panelChannelId,
                        thread.threadId,
                        content
                      )
                    }
                    onSkip={() =>
                      threadManager.skipThread(thread.threadId)
                    }
                    panelCount={threadManager.openPanelThreads.length}
                  />
                );
              }
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Thread Panel Component
// ═══════════════════════════════════════════════════════════════════════════════

function ThreadPanel({
  thread,
  appDisplay,
  appId,
  channelName,
  showApp,
  iframeRef,
  onClose,
  onDelete,
  onSend,
  onSkip,
  panelCount,
}: {
  thread: {
    threadId: string;
    appId: string;
    messages: ThreadMessage[];
    appData: Record<string, unknown> | null;
    appRefreshKey: number;
    isLoading: boolean;
    skipped: boolean;
    category: string;
  };
  appDisplay: { name: string; icon: string };
  appId: string;
  channelName?: string;
  showApp: boolean;
  iframeRef?: React.RefObject<HTMLIFrameElement | null>;
  onClose: () => void;
  onDelete: () => void;
  onSend: (content: string) => void;
  onSkip: () => void;
  panelCount: number;
}) {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // For single panel, allow resize. For multiple, use flex sizing.
  const isSingle = panelCount === 1;
  const [panelWidth, setPanelWidth] = useState(420);
  const isDragging = useRef(false);
  const startX = useRef(0);
  const startWidth = useRef(420);

  // Resize handle drag (only for single panel)
  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      if (!isSingle) return;
      isDragging.current = true;
      startX.current = e.clientX;
      startWidth.current = panelWidth;
      document.body.style.cursor = "col-resize";
      document.body.style.userSelect = "none";

      const handleMouseMove = (ev: MouseEvent) => {
        if (!isDragging.current) return;
        const delta = startX.current - ev.clientX;
        const newWidth = Math.max(
          320,
          Math.min(800, startWidth.current + delta)
        );
        setPanelWidth(newWidth);
      };

      const handleMouseUp = () => {
        isDragging.current = false;
        document.body.style.cursor = "";
        document.body.style.userSelect = "";
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };

      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
    },
    [panelWidth, isSingle]
  );

  // Auto-scroll thread messages
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [thread.messages, thread.isLoading]);

  // Get the intake question for display inside the thread panel
  const intake = getAppIntake(appId);
  const intakeQuestion = intake?.question || "";
  const skipLabel = intake?.skipLabel;

  // Build header title
  const headerTitle = channelName
    ? `${appDisplay.icon} ${appDisplay.name} • #${channelName}`
    : `${appDisplay.icon} ${appDisplay.name}`;

  return (
    <div
      className="flex flex-col shrink-0 animate-slide-in-right relative"
      style={{
        ...(isSingle
          ? { width: `${panelWidth}px` }
          : { flex: 1, minWidth: "280px" }),
        backgroundColor: "#2b2d31",
        borderLeft: "1px solid #2f3136",
      }}
    >
      {/* Resize handle (single panel only) */}
      {isSingle && (
        <div
          onMouseDown={handleMouseDown}
          className="absolute left-0 top-0 bottom-0 w-1 cursor-col-resize z-10 hover:bg-[#ff6d5a] transition-colors"
          style={{ backgroundColor: "transparent" }}
        />
      )}

      {/* ─── Thread header ─── */}
      <div
        className="flex items-center gap-2 px-3 py-2.5 shrink-0"
        style={{
          borderBottom: "1px solid #2f3136",
          backgroundColor: "#2b2d31",
        }}
      >
        <MessageSquare
          className="w-4 h-4 shrink-0"
          style={{ color: "#ff6d5a" }}
        />
        <span
          className="text-sm font-semibold truncate"
          style={{ color: "#ffffff" }}
          title={headerTitle}
        >
          {headerTitle}
        </span>
        <span
          className="text-[10px] px-1.5 py-0.5 rounded-full shrink-0"
          style={{
            backgroundColor: "rgba(255,109,90,0.15)",
            color: "#ff6d5a",
          }}
        >
          Thread
        </span>
        <div className="flex-1" />
        <button
          onClick={onDelete}
          className="p-1 rounded hover:bg-red-500/20 transition-colors"
          style={{ color: "#96989d" }}
          title="Delete thread"
        >
          <X className="w-4 h-4 hover:text-red-400" />
        </button>
        <button
          onClick={onClose}
          className="p-1 rounded hover:bg-[#383c44] transition-colors"
          style={{ color: "#96989d" }}
          title="Close panel"
        >
          <X className="w-3.5 h-3.5" />
        </button>
      </div>

      {/* ─── App iframe (shown when data ready or skipped) ─── */}
      {showApp && (
        <div
          className="shrink-0"
          style={{
            borderBottom: "1px solid #2f3136",
            maxHeight: "40%",
            overflow: "auto",
          }}
        >
          <McpAppCard
            key={`${appId}-thread`}
            ref={iframeRef}
            app={{
              id: appId,
              title: `${appDisplay.icon} ${appDisplay.name}`,
              url: `/api/mcp-apps?app=${encodeURIComponent(appId)}`,
              height: 320,
            }}
          />
        </div>
      )}

      {/* ─── Thread messages ─── */}
      <div className="flex-1 overflow-y-auto min-h-0">
        <div className="h-3" />

        {/* Intake question (first message context) */}
        <ThreadIntakeMessage
          question={intakeQuestion}
          skipLabel={skipLabel}
          skipped={thread.skipped}
          onSkip={onSkip}
          appDisplay={appDisplay}
        />

        {/* Thread conversation messages */}
        {thread.messages.map((msg) => (
          <ThreadMessageBubble key={msg.id} message={msg} />
        ))}

        {/* Typing indicator */}
        {thread.isLoading &&
          thread.messages.length > 0 &&
          thread.messages[thread.messages.length - 1]?.content === "" && (
            <div className="px-4 py-2">
              <div className="flex items-start gap-3">
                <div
                  className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 text-sm"
                  style={{ backgroundColor: "rgba(255,109,90,0.15)" }}
                >
                  🤖
                </div>
                <div className="flex items-center gap-1 py-2">
                  <span
                    className="w-2 h-2 rounded-full typing-dot"
                    style={{ backgroundColor: "#72767d" }}
                  />
                  <span
                    className="w-2 h-2 rounded-full typing-dot"
                    style={{ backgroundColor: "#72767d" }}
                  />
                  <span
                    className="w-2 h-2 rounded-full typing-dot"
                    style={{ backgroundColor: "#72767d" }}
                  />
                </div>
              </div>
            </div>
          )}

        <div ref={messagesEndRef} className="h-3" />
      </div>

      {/* ─── Thread input ─── */}
      <ChatInput
        onSend={onSend}
        disabled={thread.isLoading}
        channelName={`${appDisplay.name} Thread`}
      />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Thread message sub-components
// ═══════════════════════════════════════════════════════════════════════════════

function ThreadIntakeMessage({
  question,
  skipLabel,
  skipped,
  onSkip,
  appDisplay,
}: {
  question: string;
  skipLabel?: string;
  skipped: boolean;
  onSkip: () => void;
  appDisplay: { name: string; icon: string };
}) {
  return (
    <div className="px-4 py-2">
      <div className="flex items-start gap-3">
        {/* AI avatar */}
        <div
          className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 text-sm"
          style={{ backgroundColor: "rgba(255,109,90,0.15)" }}
        >
          🤖
        </div>

        <div className="flex-1 min-w-0">
          {/* Name + timestamp */}
          <div className="flex items-center gap-2 mb-1">
            <span
              className="text-sm font-semibold"
              style={{ color: "#ff6d5a" }}
            >
              LocalBosses AI
            </span>
            <span className="text-xs" style={{ color: "#72767d" }}>
              Thread start
            </span>
          </div>

          {/* Question text */}
          <div
            className="text-[15px] leading-relaxed"
            style={{ color: "#dcddde" }}
          >
            {question}
          </div>

          {/* Skip button */}
          {skipLabel && !skipped && (
            <button
              onClick={onSkip}
              className="mt-2 flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all duration-150 hover:brightness-125"
              style={{
                backgroundColor: "rgba(255,109,90,0.1)",
                color: "#ff6d5a",
                border: "1px solid rgba(255,109,90,0.2)",
              }}
            >
              <SkipForward className="w-3 h-3" />
              Skip → {skipLabel}
            </button>
          )}

          {/* Skipped indicator */}
          {skipped && (
            <div
              className="mt-2 flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs"
              style={{ color: "#72767d" }}
            >
              <SkipForward className="w-3 h-3" />
              Showing {skipLabel?.toLowerCase()} — refine anytime by typing
              below
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function ThreadMessageBubble({
  message,
}: {
  message: ThreadMessage;
}) {
  if (!message.content) return null;

  const isUser = message.role === "user";

  return (
    <div className="px-4 py-1.5 animate-message-in">
      <div className="flex items-start gap-3">
        {/* Avatar */}
        <div
          className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 text-sm"
          style={{
            backgroundColor: isUser
              ? "rgba(114,118,125,0.2)"
              : "rgba(255,109,90,0.15)",
          }}
        >
          {isUser ? "👤" : "🤖"}
        </div>

        <div className="flex-1 min-w-0">
          {/* Name */}
          <div className="flex items-center gap-2 mb-0.5">
            <span
              className="text-sm font-semibold"
              style={{ color: isUser ? "#ffffff" : "#ff6d5a" }}
            >
              {isUser ? "You" : "LocalBosses AI"}
            </span>
            <span className="text-xs" style={{ color: "#72767d" }}>
              {formatTime(message.timestamp)}
            </span>
          </div>

          {/* Content */}
          <div
            className="text-[15px] leading-relaxed whitespace-pre-wrap"
            style={{ color: "#dcddde" }}
          >
            {message.content}
          </div>
        </div>
      </div>
    </div>
  );
}

function formatTime(date: Date): string {
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);

  if (minutes < 1) return "Just now";
  if (minutes < 60) return `${minutes}m ago`;
  return date.toLocaleTimeString("en-US", {
    hour: "numeric",
    minute: "2-digit",
  });
}

// ═══════════════════════════════════════════════════════════════════════════════
// Welcome screen
// ═══════════════════════════════════════════════════════════════════════════════

function WelcomeScreen({
  channelId,
  channelName,
}: {
  channelId: string;
  channelName: string;
}) {
  if (channelId === "general") {
    return (
      <div className="text-center max-w-lg px-4">
        <div className="mb-6">
          <div
            className="w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4"
            style={{ backgroundColor: "rgba(255,109,90,0.15)" }}
          >
            <Flame className="w-10 h-10" style={{ color: "#ff6d5a" }} />
          </div>
          <h2
            className="text-2xl font-bold mb-2"
            style={{ color: "#ffffff" }}
          >
            Welcome to LocalBosses AI 🔥
          </h2>
          <p className="text-sm mb-6" style={{ color: "#96989d" }}>
            Your AI-powered business operations platform. Each channel is a
            specialist:
          </p>
        </div>

        <div className="text-left space-y-3 mb-6">
          {[
            {
              icon: "⚡",
              name: "#automations",
              desc: "Build n8n workflows with natural language",
            },
            {
              icon: "👥",
              name: "#crm",
              desc: "Manage your CRM, contacts, and pipelines",
            },
            {
              icon: "📋",
              name: "#templates",
              desc: "Browse 2,700+ automation templates",
            },
            {
              icon: "🔧",
              name: "#nodes",
              desc: "Explore 1,084+ integration nodes",
            },
            {
              icon: "💚",
              name: "#health",
              desc: "Monitor system status",
            },
          ].map((item) => (
            <div
              key={item.name}
              className="flex items-start gap-3 px-4 py-2.5 rounded-lg"
              style={{ backgroundColor: "rgba(255,109,90,0.05)" }}
            >
              <span className="text-lg">{item.icon}</span>
              <div>
                <span
                  className="text-sm font-semibold"
                  style={{ color: "#ff6d5a" }}
                >
                  {item.name}
                </span>
                <span
                  className="text-sm ml-2"
                  style={{ color: "#96989d" }}
                >
                  — {item.desc}
                </span>
              </div>
            </div>
          ))}
        </div>

        <p className="text-sm" style={{ color: "#72767d" }}>
          Just pick a channel and start chatting!
        </p>
      </div>
    );
  }

  // Other channel welcome
  const channel = getChannel(channelId);
  const iconMap: Record<string, string> = {
    automations: "⚡",
    crm: "👥",
    templates: "📋",
    nodes: "🔧",
    health: "💚",
  };

  return (
    <div className="text-center max-w-md px-4">
      <div
        className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 text-3xl"
        style={{ backgroundColor: "rgba(255,109,90,0.15)" }}
      >
        {iconMap[channelId] || "💬"}
      </div>
      <h2 className="text-xl font-bold mb-2" style={{ color: "#ffffff" }}>
        Welcome to #{channelName}
      </h2>
      <p className="text-sm" style={{ color: "#96989d" }}>
        {channel?.description || "Start a conversation"}
      </p>
      {channel?.mcpApps && channel.mcpApps.length > 0 && (
        <p
          className="text-xs mt-3 px-3 py-1.5 rounded-full inline-block"
          style={{
            backgroundColor: "rgba(255,109,90,0.1)",
            color: "#ff6d5a",
          }}
        >
          {channel.mcpApps.length} MCP Apps available — use the toolbar above
        </p>
      )}
    </div>
  );
}
