// src/components/templates/messaging/ConversationList.tsx
import { useQuery } from "@apollo/client/react";
import { gql } from "@apollo/client";
import { MessageCircle, Users } from "lucide-react";
import { useMemo } from "react";
import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
import { jsx, jsxs } from "react/jsx-runtime";
var CONVERSATIONS_QUERY = gql`
  query Conversations($projectId: ID!) {
    conversations(projectId: $projectId) {
      id
      name
      isGroup
      updatedAt
      participants {
        id
        userId
        displayName
      }
    }
  }
`;
function ConversationList({
  selectedId,
  onSelect
}) {
  const { projectId } = useTemplateRuntime();
  const { data, loading } = useQuery(CONVERSATIONS_QUERY, {
    variables: { projectId },
    fetchPolicy: "cache-and-network"
  });
  const conversations = useMemo(() => data?.conversations ?? [], [data]);
  return /* @__PURE__ */ jsxs("aside", {
    className: "border-border bg-card h-full overflow-y-auto rounded-2xl border",
    children: [
      /* @__PURE__ */ jsxs("header", {
        className: "border-border px -4 flex items-center justify-between border-b px-4 py-3",
        children: [
          /* @__PURE__ */ jsxs("div", {
            children: [
              /* @__PURE__ */ jsx("p", {
                className: "text-sm font-semibold",
                children: "Conversations"
              }),
              /* @__PURE__ */ jsx("p", {
                className: "text-muted-foreground text-xs",
                children: loading ? "Loading…" : `${conversations.length} active`
              })
            ]
          }),
          /* @__PURE__ */ jsx(Users, {
            className: "text-muted-foreground h-4 w-4"
          })
        ]
      }),
      /* @__PURE__ */ jsxs("div", {
        className: "divide-border/70 divide-y",
        children: [
          conversations.map((conversation) => {
            const isSelected = selectedId === conversation.id;
            return /* @__PURE__ */ jsxs("button", {
              type: "button",
              className: `flex w-full flex-col items-start gap-1 px-4 py-3 text-left transition ${isSelected ? "text-foreground bg-violet-500/10" : "hover:bg-muted/40"}`,
              onClick: () => onSelect?.(conversation.id),
              children: [
                /* @__PURE__ */ jsxs("div", {
                  className: "flex items-center gap-2",
                  children: [
                    /* @__PURE__ */ jsx(MessageCircle, {
                      className: "text-muted-foreground h-4 w-4"
                    }),
                    /* @__PURE__ */ jsx("span", {
                      className: "text-sm font-medium",
                      children: conversation.name || "Untitled conversation"
                    })
                  ]
                }),
                /* @__PURE__ */ jsx("p", {
                  className: "text-muted-foreground text-xs",
                  children: conversation.participants.map((participant) => participant.displayName || participant.userId).join(" · ")
                })
              ]
            }, conversation.id);
          }),
          !loading && conversations.length === 0 ? /* @__PURE__ */ jsx("p", {
            className: "text-muted-foreground p-4 text-center text-xs",
            children: "No conversations yet."
          }) : null
        ]
      })
    ]
  });
}

// src/components/templates/messaging/MessageThread.tsx
import { useMutation, useQuery as useQuery2 } from "@apollo/client/react";
import { gql as gql2 } from "@apollo/client";
import { useEffect, useRef } from "react";
import { useTemplateRuntime as useTemplateRuntime2 } from "@contractspec/lib.example-shared-ui";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
"use client";
var MESSAGES_QUERY = gql2`
  query Messages($conversationId: ID!) {
    messages(conversationId: $conversationId, limit: 50) {
      id
      content
      senderId
      senderName
      createdAt
      status
    }
  }
`;
var SET_READ = gql2`
  mutation SetMessagesRead($conversationId: ID!, $userId: String!) {
    setMessagesRead(conversationId: $conversationId, userId: $userId)
  }
`;
function MessageThread({
  conversationId,
  viewerId = "local-user"
}) {
  const scrollRef = useRef(null);
  const enabled = Boolean(conversationId);
  const { data, loading } = useQuery2(MESSAGES_QUERY, {
    variables: { conversationId },
    skip: !enabled,
    fetchPolicy: "cache-and-network"
  });
  const [setRead] = useMutation(SET_READ);
  const { projectId } = useTemplateRuntime2();
  const messages = data?.messages ?? [];
  useEffect(() => {
    if (!enabled || !conversationId)
      return;
    setRead({ variables: { conversationId, userId: viewerId } }).catch(() => {});
  }, [conversationId, enabled, setRead, viewerId]);
  useEffect(() => {
    const container = scrollRef.current;
    if (!container)
      return;
    container.scrollTop = container.scrollHeight;
  }, [messages]);
  if (!conversationId) {
    return /* @__PURE__ */ jsx2("div", {
      className: "border-border flex flex-1 items-center justify-center rounded-2xl border border-dashed",
      children: /* @__PURE__ */ jsx2("p", {
        className: "text-muted-foreground text-sm",
        children: "Select a conversation"
      })
    });
  }
  return /* @__PURE__ */ jsx2("div", {
    className: "border-border bg-card flex flex-1 flex-col rounded-2xl border",
    children: /* @__PURE__ */ jsx2("div", {
      ref: scrollRef,
      className: "flex-1 space-y-3 overflow-y-auto p-4",
      children: loading ? /* @__PURE__ */ jsx2("p", {
        className: "text-muted-foreground text-center text-sm",
        children: "Loading…"
      }) : messages.slice().reverse().map((message) => /* @__PURE__ */ jsxs2("div", {
        className: `flex flex-col ${message.senderId === viewerId ? "items-end" : "items-start"}`,
        children: [
          /* @__PURE__ */ jsx2("div", {
            className: `max-w-xs rounded-2xl px-3 py-2 text-sm ${message.senderId === viewerId ? "bg-violet-500 text-white" : "bg-muted text-foreground"}`,
            children: /* @__PURE__ */ jsx2("p", {
              children: message.content
            })
          }),
          /* @__PURE__ */ jsxs2("span", {
            className: "text-muted-foreground mt-1 text-xs",
            children: [
              message.senderName || message.senderId,
              " ·",
              " ",
              new Date(message.createdAt).toLocaleTimeString([], {
                hour: "2-digit",
                minute: "2-digit"
              })
            ]
          })
        ]
      }, message.id))
    })
  });
}

// src/components/templates/messaging/MessageComposer.tsx
import { useState } from "react";
import { useMutation as useMutation2 } from "@apollo/client/react";
import { gql as gql3 } from "@apollo/client";
import { Send } from "lucide-react";
import { useTemplateRuntime as useTemplateRuntime3 } from "@contractspec/lib.example-shared-ui";
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
"use client";
var SEND_MESSAGE = gql3`
  mutation SendMessage($input: SendMessageInput!) {
    sendMessage(input: $input) {
      id
    }
  }
`;
function MessageComposer({
  conversationId,
  viewerId = "local-user",
  viewerName = "You"
}) {
  const { projectId } = useTemplateRuntime3();
  const [content, setContent] = useState("");
  const [sendMessage, { loading }] = useMutation2(SEND_MESSAGE);
  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!conversationId || !content.trim())
      return;
    await sendMessage({
      variables: {
        input: {
          projectId,
          conversationId,
          senderId: viewerId,
          senderName: viewerName,
          content: content.trim()
        }
      },
      refetchQueries: [
        {
          query: MESSAGES_QUERY,
          variables: { conversationId }
        }
      ]
    });
    setContent("");
  };
  return /* @__PURE__ */ jsxs3("form", {
    onSubmit: handleSubmit,
    className: "border-border bg-card mt-3 flex items-center gap-2 rounded-2xl border px-4 py-3",
    children: [
      /* @__PURE__ */ jsx3("input", {
        type: "text",
        className: "text-foreground flex-1 bg-transparent text-sm outline-none",
        placeholder: conversationId ? "Type a message…" : "Select a conversation to start",
        disabled: !conversationId || loading,
        value: content,
        onChange: (event) => setContent(event.target.value)
      }),
      /* @__PURE__ */ jsxs3("button", {
        type: "submit",
        className: "btn-primary inline-flex items-center gap-1 text-sm",
        disabled: !conversationId || loading || !content.trim(),
        children: [
          /* @__PURE__ */ jsx3(Send, {
            className: "h-4 w-4"
          }),
          "Send"
        ]
      })
    ]
  });
}

// src/components/templates/messaging/MessagingWorkspace.tsx
import { useState as useState2 } from "react";
import { registerTemplateComponents } from "@contractspec/lib.example-shared-ui";
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
"use client";
function MessagingWorkspace() {
  const [conversationId, setConversationId] = useState2();
  return /* @__PURE__ */ jsxs4("div", {
    className: "grid gap-4 md:grid-cols-[280px,1fr]",
    children: [
      /* @__PURE__ */ jsx4(ConversationList, {
        selectedId: conversationId,
        onSelect: setConversationId
      }),
      /* @__PURE__ */ jsxs4("div", {
        className: "flex flex-col gap-3",
        children: [
          /* @__PURE__ */ jsx4(MessageThread, {
            conversationId
          }),
          /* @__PURE__ */ jsx4(MessageComposer, {
            conversationId
          })
        ]
      })
    ]
  });
}
registerTemplateComponents("messaging-app", {
  list: MessagingWorkspace,
  detail: MessageThread,
  form: MessageComposer
});
export {
  MessagingWorkspace,
  MessageThread,
  MessageComposer,
  MESSAGES_QUERY,
  ConversationList
};
