/**
* GeneralDiscussionFloater - Floating panel for whole-bill general discussions
*
* Appears as a modal/overlay panel when user clicks "General Discussion"
* in inline comments mode. Allows commenting on the bill as a whole.
*/
'use client';
import React, { useState, useRef, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { createPost, deletePost } from '@/actions/forum';
import { reportPost } from '@/actions/moderation';
import { VoteButtons } from '@/components/forum/VoteButtons';
import type { ForumPost } from '@/types/forum';
import {
MessageSquare,
X,
Send,
MoreHorizontal,
Reply,
Flag,
Trash2,
User,
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { fr, enUS } from 'date-fns/locale';
interface GeneralDiscussionFloaterProps {
billNumber: string;
session: string;
locale: string;
comments: ForumPost[];
isOpen: boolean;
onClose: () => void;
onCommentCreated?: () => void;
}
const MAX_CONTENT_PREVIEW = 200;
/**
* Single comment display with voting and actions
*/
function CommentItem({
comment,
locale,
onDelete,
onReport,
onReply,
onVoteChange,
isReply = false,
showReplies = true,
}: {
comment: ForumPost;
locale: string;
onDelete?: (id: string) => void;
onReport?: (id: string) => void;
onReply?: (id: string) => void;
onVoteChange?: () => void;
isReply?: boolean;
showReplies?: boolean;
}) {
const { user } = useAuth();
const [showMenu, setShowMenu] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const isOwner = user?.id === comment.author_id;
const dateLocale = locale === 'fr' ? fr : enUS;
const contentTruncated = comment.content.length > MAX_CONTENT_PREVIEW && !isExpanded;
const displayContent = contentTruncated
? comment.content.slice(0, MAX_CONTENT_PREVIEW) + '...'
: comment.content;
return (
<div className={`${isReply ? 'ml-4 pl-4 border-l-2 border-slate-600' : ''}`}>
<div className="py-3">
{/* Author row */}
<div className="flex items-center gap-2 mb-2">
{comment.author_avatar_url ? (
<img
src={comment.author_avatar_url}
alt={comment.author_name || 'User'}
className="w-8 h-8 rounded-full object-cover"
/>
) : (
<div className="w-8 h-8 rounded-full bg-slate-600 flex items-center justify-center">
<User className="w-4 h-4 text-slate-400" />
</div>
)}
<div className="flex-1 min-w-0">
<span className="text-sm font-medium text-slate-200 block truncate">
{comment.author_name || (locale === 'fr' ? 'Anonyme' : 'Anonymous')}
</span>
<span className="text-xs text-slate-500">
{formatDistanceToNow(new Date(comment.created_at), {
addSuffix: true,
locale: dateLocale,
})}
</span>
</div>
</div>
{/* Content */}
<p className="text-sm text-slate-300 leading-relaxed whitespace-pre-wrap mb-2">
{displayContent}
</p>
{comment.content.length > MAX_CONTENT_PREVIEW && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="text-xs text-blue-400 hover:text-blue-300 mb-2"
>
{isExpanded
? (locale === 'fr' ? 'Voir moins' : 'Show less')
: (locale === 'fr' ? 'Voir plus' : 'Show more')}
</button>
)}
{/* Actions row */}
<div className="flex items-center gap-4">
<VoteButtons
postId={comment.id}
upvotes={comment.upvotes_count}
downvotes={comment.downvotes_count}
userVote={comment.user_vote}
size="sm"
layout="horizontal"
onVoteChange={onVoteChange ? () => onVoteChange() : undefined}
/>
{onReply && user && (
<button
onClick={() => onReply(comment.id)}
className="text-xs text-slate-400 hover:text-slate-200 flex items-center gap-1"
>
<Reply className="w-3.5 h-3.5" />
{locale === 'fr' ? 'Répondre' : 'Reply'}
</button>
)}
{/* Menu */}
<div className="relative ml-auto">
<button
onClick={() => setShowMenu(!showMenu)}
className="p-1 text-slate-500 hover:text-slate-300 rounded"
>
<MoreHorizontal className="w-4 h-4" />
</button>
{showMenu && (
<>
<div
className="fixed inset-0 z-10"
onClick={() => setShowMenu(false)}
/>
<div className="absolute right-0 top-full mt-1 bg-slate-700 rounded shadow-lg z-20 min-w-[120px] py-1">
{isOwner && onDelete && (
<button
onClick={() => {
onDelete(comment.id);
setShowMenu(false);
}}
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm text-red-400 hover:bg-slate-600"
>
<Trash2 className="w-3.5 h-3.5" />
{locale === 'fr' ? 'Supprimer' : 'Delete'}
</button>
)}
{!isOwner && onReport && user && (
<button
onClick={() => {
onReport(comment.id);
setShowMenu(false);
}}
className="w-full flex items-center gap-2 px-3 py-1.5 text-sm text-slate-300 hover:bg-slate-600"
>
<Flag className="w-3.5 h-3.5" />
{locale === 'fr' ? 'Signaler' : 'Report'}
</button>
)}
</div>
</>
)}
</div>
</div>
</div>
{/* Nested replies */}
{showReplies && comment.replies && comment.replies.length > 0 && (
<div className="mt-1">
{comment.replies.map((reply) => (
<CommentItem
key={reply.id}
comment={reply}
locale={locale}
onDelete={onDelete}
onReport={onReport}
onVoteChange={onVoteChange}
isReply={true}
/>
))}
</div>
)}
</div>
);
}
/**
* Comment form for general discussion
*/
function CommentForm({
billNumber,
session,
locale,
onSuccess,
onCancel,
parentPostId,
autoFocus = false,
}: {
billNumber: string;
session: string;
locale: string;
onSuccess?: () => void;
onCancel?: () => void;
parentPostId?: string;
autoFocus?: boolean;
}) {
const { user } = useAuth();
const [content, setContent] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (autoFocus && textareaRef.current) {
textareaRef.current.focus();
}
}, [autoFocus]);
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 150)}px`;
}
}, [content]);
if (!user) {
return (
<div className="text-center py-3">
<a
href="/auth/signin"
className="text-sm text-blue-400 hover:text-blue-300"
>
{locale === 'fr' ? 'Connectez-vous pour commenter' : 'Sign in to comment'}
</a>
</div>
);
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim() || isSubmitting) return;
setIsSubmitting(true);
setError(null);
try {
const autoTitle = `General comment on ${session}/${billNumber}`;
const result = await createPost({
post_type: 'bill_comment',
bill_number: billNumber,
bill_session: session,
title: autoTitle,
content: content.trim(),
entity_metadata: { section_ref: 'general' },
parent_post_id: parentPostId,
});
if (result.success) {
setContent('');
onSuccess?.();
} else {
setError(result.error || (locale === 'fr' ? 'Erreur' : 'Error'));
}
} catch (err) {
setError(locale === 'fr' ? 'Une erreur est survenue' : 'An error occurred');
} finally {
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit} className="relative">
<textarea
ref={textareaRef}
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={
parentPostId
? (locale === 'fr' ? 'Votre réponse...' : 'Your reply...')
: (locale === 'fr' ? 'Partagez votre opinion sur ce projet de loi...' : 'Share your thoughts on this bill...')
}
className="w-full px-4 py-3 pr-12 text-sm bg-slate-700 border border-slate-600 rounded-lg text-slate-200 placeholder-slate-500 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 min-h-[80px] max-h-[150px]"
rows={3}
disabled={isSubmitting}
/>
{/* Submit button */}
<button
type="submit"
disabled={!content.trim() || isSubmitting}
className="absolute right-3 bottom-3 p-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
<Send className="w-4 h-4" />
</button>
{error && (
<p className="text-xs text-red-400 mt-1">{error}</p>
)}
{onCancel && (
<button
type="button"
onClick={onCancel}
className="text-xs text-slate-500 hover:text-slate-300 mt-2"
>
{locale === 'fr' ? 'Annuler' : 'Cancel'}
</button>
)}
</form>
);
}
/**
* Build threaded tree from flat list
*/
function buildThreadTree(posts: ForumPost[]): ForumPost[] {
const postMap = new Map<string, ForumPost & { replies: ForumPost[] }>();
posts.forEach((post) => {
postMap.set(post.id, { ...post, replies: [] });
});
const topLevelPosts: ForumPost[] = [];
posts.forEach((post) => {
const postWithReplies = postMap.get(post.id)!;
if (post.parent_post_id && postMap.has(post.parent_post_id)) {
const parent = postMap.get(post.parent_post_id)!;
parent.replies.push(postWithReplies);
} else {
topLevelPosts.push(postWithReplies);
}
});
// Sort by votes then by date
topLevelPosts.sort((a, b) => {
const aScore = (a.upvotes_count || 0) - (a.downvotes_count || 0);
const bScore = (b.upvotes_count || 0) - (b.downvotes_count || 0);
if (bScore !== aScore) return bScore - aScore;
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
});
return topLevelPosts;
}
/**
* Main floating panel component
*/
export function GeneralDiscussionFloater({
billNumber,
session,
locale,
comments,
isOpen,
onClose,
onCommentCreated,
}: GeneralDiscussionFloaterProps) {
const [replyingTo, setReplyingTo] = useState<string | null>(null);
const threadedComments = buildThreadTree(comments);
const totalCount = comments.length;
const handleDelete = async (postId: string) => {
const result = await deletePost(postId);
if (result.success) {
onCommentCreated?.();
} else {
alert(result.error || (locale === 'fr' ? 'Échec de la suppression' : 'Failed to delete'));
}
};
const handleReport = async (postId: string) => {
const result = await reportPost({ post_id: postId, reason: 'other' });
if (result.success) {
alert(locale === 'fr' ? 'Merci pour votre signalement' : 'Thank you for your report');
} else {
alert(result.error || (locale === 'fr' ? 'Échec du signalement' : 'Failed to report'));
}
};
const handleReply = (postId: string) => {
setReplyingTo(postId);
};
const handleReplySuccess = () => {
setReplyingTo(null);
onCommentCreated?.();
};
return (
<>
{/* Backdrop - only visible when open */}
<div
className={`fixed inset-0 bg-black/30 z-40 transition-opacity duration-300 ${
isOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'
}`}
onClick={onClose}
/>
{/* Right-side Panel */}
<div
className={`fixed top-0 right-0 h-full w-full sm:w-96 bg-slate-800 border-l border-slate-700 shadow-2xl z-50 flex flex-col transform transition-transform duration-300 ease-in-out ${
isOpen ? 'translate-x-0' : 'translate-x-full'
}`}
>
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-700 bg-slate-900 flex-shrink-0">
<div className="flex items-center gap-3">
<MessageSquare className="w-5 h-5 text-blue-400" />
<div>
<h2 className="text-base font-semibold text-slate-200">
{locale === 'fr' ? 'Discussion générale' : 'General Discussion'}
</h2>
<p className="text-xs text-slate-500">
{locale === 'fr' ? `Projet de loi ${billNumber}` : `Bill ${billNumber}`}
</p>
</div>
{totalCount > 0 && (
<span className="text-sm bg-blue-600 text-white px-2 py-0.5 rounded-full">
{totalCount}
</span>
)}
</div>
<button
onClick={onClose}
className="p-2 text-slate-500 hover:text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-4">
{/* Comment form */}
<div className="mb-4">
<CommentForm
billNumber={billNumber}
session={session}
locale={locale}
onSuccess={onCommentCreated}
/>
</div>
{/* Divider */}
{totalCount > 0 && (
<div className="border-t border-slate-700 my-4" />
)}
{/* Comments list */}
{totalCount === 0 ? (
<div className="text-center py-8">
<MessageSquare className="w-12 h-12 mx-auto text-slate-600 mb-3" />
<p className="text-sm text-slate-500">
{locale === 'fr'
? 'Soyez le premier à partager votre opinion'
: 'Be the first to share your thoughts'}
</p>
</div>
) : (
<div className="space-y-1 divide-y divide-slate-700">
{threadedComments.map((comment) => (
<div key={comment.id}>
<CommentItem
comment={comment}
locale={locale}
onDelete={handleDelete}
onReport={handleReport}
onReply={handleReply}
onVoteChange={onCommentCreated}
showReplies={true}
/>
{/* Reply form */}
{replyingTo === comment.id && (
<div className="mt-2 ml-4 pl-4 border-l-2 border-slate-600">
<CommentForm
billNumber={billNumber}
session={session}
locale={locale}
onSuccess={handleReplySuccess}
onCancel={() => setReplyingTo(null)}
parentPostId={comment.id}
autoFocus={true}
/>
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
</>
);
}
export default GeneralDiscussionFloater;