'use client' export const dynamic = 'force-dynamic' import { Suspense, useEffect, useMemo, useState, useRef, useCallback } from 'react' import { useRouter, useSearchParams } from 'next/navigation' import { postService } from '@/services/postService' import { reelService } from '@/services/reelService' import { storyService } from '@/services/storyService' import { githubService } from '@/services/githubService' import { repoService } from '@/services/repoService' import { draftService } from '@/services/draftService' import { useToast } from '@/components/ui/toast' import MentionInput from '@/components/MentionInput' import CodeSnippetEmbed, { CodeSnippetEditor } from '@/components/CodeSnippetEmbed' import api from '@/services/api' import { getErrorMessage } from '@/utils/error' import { buildRepoPath } from '@/utils/repositoryRouting' type ComposeType = 'post' | 'reel' | 'story' | 'change_story' interface RepoOption { id?: string owner: string name: string fullName?: string } interface CodeSnippetData { id: string code: string language: string filePath?: string lineStart?: number lineEnd?: number } interface MediaPreview { file: File url: string type: 'image' | 'video' } function ComposeContent() { const router = useRouter() const searchParams = useSearchParams() const { showToast } = useToast() const queryType = (searchParams.get('type') || 'post') as ComposeType const queryOwner = searchParams.get('owner') || '' const queryName = searchParams.get('name') || '' const queryCheckpointId = searchParams.get('checkpointId') || '' const queryFromCheckpointId = searchParams.get('fromCheckpointId') || '' const queryAitmProjectId = searchParams.get('projectId') || searchParams.get('aitmProjectId') || '' const queryTitle = searchParams.get('title') || '' const queryContent = searchParams.get('content') || '' const queryCaption = searchParams.get('caption') || '' const queryDiffAdded = searchParams.get('diffAdded') || '0' const queryDiffRemoved = searchParams.get('diffRemoved') || '0' const queryDiffModified = searchParams.get('diffModified') || '0' const queryChangedFiles = searchParams.get('changedFiles') || '' const queryDraftId = searchParams.get('draftId') || '' const [type, setType] = useState( ['post', 'reel', 'story', 'change_story'].includes(queryType) ? queryType : 'post' ) // Repository state const [repos, setRepos] = useState([]) const [selectedRepo, setSelectedRepo] = useState('') const [loadingRepos, setLoadingRepos] = useState(false) // Content state const [content, setContent] = useState(queryContent) const [caption, setCaption] = useState(queryCaption) const [hashtags, setHashtags] = useState('') const [hashtagSuggestions, setHashtagSuggestions] = useState([]) // Media state const [mediaPreviews, setMediaPreviews] = useState([]) const [isDragging, setIsDragging] = useState(false) const fileInputRef = useRef(null) const dropZoneRef = useRef(null) // Code snippet state const [codeSnippets, setCodeSnippets] = useState([]) const [showSnippetEditor, setShowSnippetEditor] = useState(false) // Markdown preview const [showPreview, setShowPreview] = useState(false) // Scheduling const [showScheduler, setShowScheduler] = useState(false) const [scheduledDate, setScheduledDate] = useState('') const [scheduledTime, setScheduledTime] = useState('') // Change story state const [changeTitle, setChangeTitle] = useState(queryTitle || 'Repository Change Story') const [checkpointId, setCheckpointId] = useState(queryCheckpointId) const [fromCheckpointId, setFromCheckpointId] = useState(queryFromCheckpointId) const [aitmProjectId, setAitmProjectId] = useState(queryAitmProjectId) const [diffAdded, setDiffAdded] = useState(queryDiffAdded) const [diffRemoved, setDiffRemoved] = useState(queryDiffRemoved) const [diffModified, setDiffModified] = useState(queryDiffModified) const [changedFiles, setChangedFiles] = useState(queryChangedFiles) // AITM project selection for change stories const [aitmProjects, setAitmProjects] = useState([]) const [aitmCheckpoints, setAitmCheckpoints] = useState([]) const [loadingCheckpoints, setLoadingCheckpoints] = useState(false) const [autoGeneratingDiff, setAutoGeneratingDiff] = useState(false) // General state const [submitting, setSubmitting] = useState(false) const [error, setError] = useState('') const [savingDraft, setSavingDraft] = useState(false) const [currentDraftId, setCurrentDraftId] = useState(queryDraftId) const [lastSaved, setLastSaved] = useState(null) // Load repos on mount useEffect(() => { const load = async () => { setLoadingRepos(true) try { const data = await githubService.getProjects() const projectOptions: RepoOption[] = (data.projects || []).map((p: any) => ({ id: p.id, owner: p.owner, name: p.name, fullName: p.fullName || `${p.owner}/${p.name}`, })) setRepos(projectOptions) const pre = queryOwner && queryName ? `${queryOwner}/${queryName}` : '' if (pre && projectOptions.some((p) => `${p.owner}/${p.name}` === pre)) { setSelectedRepo(pre) } else if (projectOptions[0]) { setSelectedRepo(`${projectOptions[0].owner}/${projectOptions[0].name}`) } } catch { // Repos may fail silently } finally { setLoadingRepos(false) } } void load() }, [queryOwner, queryName]) // Load draft if draftId provided useEffect(() => { if (queryDraftId) { const loadDraft = async () => { const draft = await draftService.getDraft(queryDraftId) if (draft) { setContent(draft.content || '') setCurrentDraftId(draft.id) } } void loadDraft() } }, [queryDraftId]) // Load AITM projects for change stories useEffect(() => { if (type === 'change_story') { const loadAitmProjects = async () => { try { const { data } = await api.get('/aitm/projects') setAitmProjects(data.projects || []) } catch { // AITM may not be available } } void loadAitmProjects() } }, [type]) // Load checkpoints when AITM project is selected useEffect(() => { if (aitmProjectId) { const loadCheckpoints = async () => { setLoadingCheckpoints(true) try { const { data } = await api.get(`/aitm/projects/${aitmProjectId}/checkpoints`) setAitmCheckpoints(data.checkpoints || []) } catch { setAitmCheckpoints([]) } finally { setLoadingCheckpoints(false) } } void loadCheckpoints() } }, [aitmProjectId]) // Auto-generate diff when both checkpoints are selected const handleAutoGenerateDiff = useCallback(async () => { if (!fromCheckpointId || !checkpointId || !aitmProjectId) return setAutoGeneratingDiff(true) try { const { data } = await api.get( `/aitm/projects/${aitmProjectId}/diff?from=${fromCheckpointId}&to=${checkpointId}` ) if (data.diff) { setDiffAdded(String(data.diff.added || 0)) setDiffRemoved(String(data.diff.removed || 0)) setDiffModified(String(data.diff.modified || 0)) if (data.diff.changedFiles) { setChangedFiles(data.diff.changedFiles.join('\n')) } if (data.diff.summary) { setContent(data.diff.summary) } showToast('Diff summary generated', 'success') } } catch { showToast('Could not auto-generate diff. Fill in manually.', 'warning') } finally { setAutoGeneratingDiff(false) } }, [fromCheckpointId, checkpointId, aitmProjectId, showToast]) const repo = useMemo(() => { const [owner, name] = selectedRepo.split('/') return owner && name ? { owner, name } : null }, [selectedRepo]) // Hashtag suggestion handling const handleHashtagInput = async (value: string) => { setHashtags(value) const parts = value.split(',') const lastTag = parts[parts.length - 1]?.trim() if (lastTag && lastTag.length > 1) { try { const { data } = await api.get('/tags/search', { params: { q: lastTag.replace('#', ''), limit: 5 } }) setHashtagSuggestions( (data.hashtags || data || []).map((h: any) => h.name || h) ) } catch { setHashtagSuggestions([]) } } else { setHashtagSuggestions([]) } } const insertHashtag = (tag: string) => { const parts = hashtags.split(',').map((p) => p.trim()).filter(Boolean) parts[parts.length - 1] = tag setHashtags(parts.join(', ')) setHashtagSuggestions([]) } // Media handling with drag-and-drop const processFiles = (files: FileList | File[]) => { const newPreviews: MediaPreview[] = [] Array.from(files).forEach((file) => { if (file.type.startsWith('image/') || file.type.startsWith('video/')) { newPreviews.push({ file, url: URL.createObjectURL(file), type: file.type.startsWith('video/') ? 'video' : 'image', }) } }) setMediaPreviews((prev) => [...prev, ...newPreviews]) } const handleDragOver = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() setIsDragging(true) } const handleDragLeave = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() setIsDragging(false) } const handleDrop = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() setIsDragging(false) if (e.dataTransfer.files.length > 0) { processFiles(e.dataTransfer.files) } } const handleFileSelect = (e: React.ChangeEvent) => { if (e.target.files) { processFiles(e.target.files) } } const removeMedia = (index: number) => { setMediaPreviews((prev) => { const updated = [...prev] URL.revokeObjectURL(updated[index].url) updated.splice(index, 1) return updated }) } // Code snippet handling const handleInsertSnippet = (snippet: Omit) => { const newSnippet: CodeSnippetData = { ...snippet, id: `snippet_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, } setCodeSnippets((prev) => [...prev, newSnippet]) setShowSnippetEditor(false) } const removeSnippet = (id: string) => { setCodeSnippets((prev) => prev.filter((s) => s.id !== id)) } // Markdown toolbar actions const insertMarkdown = (before: string, after: string = '') => { const textarea = document.querySelector('textarea[data-compose-editor]') as HTMLTextAreaElement if (!textarea) return const start = textarea.selectionStart const end = textarea.selectionEnd const selected = content.substring(start, end) const newContent = content.substring(0, start) + before + selected + after + content.substring(end) setContent(newContent) setTimeout(() => { textarea.focus() const cursorPos = start + before.length + selected.length + after.length textarea.setSelectionRange(cursorPos, cursorPos) }, 0) } // Simple markdown to HTML for preview const renderMarkdownPreview = (text: string): string => { return text .replace(/^### (.*$)/gm, '

$1

') .replace(/^## (.*$)/gm, '

$1

') .replace(/^# (.*$)/gm, '

$1

') .replace(/\*\*([^*]+)\*\*/g, '$1') .replace(/\*([^*]+)\*/g, '$1') .replace(/`([^`]+)`/g, '$1') .replace(/```(\w*)\n([\s\S]*?)```/g, '
$2
') .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1') .replace(/^- (.*$)/gm, '
  • $1
  • ') .replace(/\n/g, '
    ') } // Draft saving const saveDraft = async () => { if (!content.trim() && codeSnippets.length === 0) return setSavingDraft(true) try { const draftContent = JSON.stringify({ type, content, caption, hashtags, selectedRepo, codeSnippets, changeTitle, checkpointId, fromCheckpointId, aitmProjectId, }) if (currentDraftId) { await draftService.updateDraft(currentDraftId, draftContent) } else { const draft = await draftService.createDraft(draftContent) setCurrentDraftId(draft.id) } setLastSaved(new Date()) showToast('Draft saved', 'success') } catch { showToast('Failed to save draft', 'error') } finally { setSavingDraft(false) } } // Auto-save every 30 seconds if content changes useEffect(() => { const interval = setInterval(() => { if (content.trim() || caption.trim()) { saveDraft() } }, 30000) return () => clearInterval(interval) // eslint-disable-next-line react-hooks/exhaustive-deps }, [content, caption, currentDraftId]) const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setError('') if (!repo && type !== 'change_story') { setError('Select a repository first.') return } // Check if scheduling if (showScheduler && scheduledDate && scheduledTime) { const scheduledAt = new Date(`${scheduledDate}T${scheduledTime}`) if (scheduledAt <= new Date()) { setError('Scheduled time must be in the future.') return } } setSubmitting(true) try { if (type === 'post') { if (!content.trim() && mediaPreviews.length === 0 && codeSnippets.length === 0) { setError('Add post content, media, or a code snippet.') setSubmitting(false) return } // Build content with embedded snippets let fullContent = content if (codeSnippets.length > 0) { codeSnippets.forEach((snippet) => { fullContent += `\n\n\`\`\`${snippet.language}${snippet.filePath ? ` // ${snippet.filePath}` : ''}\n${snippet.code}\n\`\`\`` }) } const formData = new FormData() formData.append('content', fullContent) if (repo) { formData.append('repoOwner', repo.owner) formData.append('repoName', repo.name) } if (hashtags.trim()) formData.append('hashtags', hashtags) if (mediaPreviews.length > 0) { formData.append('media', mediaPreviews[0].file) } // Additional media files mediaPreviews.slice(1).forEach((preview, i) => { formData.append(`media_${i + 1}`, preview.file) }) if (showScheduler && scheduledDate && scheduledTime) { formData.append('scheduledAt', new Date(`${scheduledDate}T${scheduledTime}`).toISOString()) await api.post('/scheduled-posts', formData, { headers: { 'Content-Type': 'multipart/form-data' }, }) showToast('Post scheduled', 'success') } else { if (checkpointId.trim() && aitmProjectId.trim()) { await postService.createPostWithCheckpoint(formData, { checkpointId: checkpointId.trim(), projectId: aitmProjectId.trim(), fromCheckpointId: fromCheckpointId.trim() || undefined, diffSummary: { added: Number(diffAdded || 0), removed: Number(diffRemoved || 0), modified: Number(diffModified || 0), }, changedFiles: changedFiles .split('\n') .map((line) => line.trim()) .filter(Boolean), changeStoryTitle: changeTitle.trim() || undefined, }) } else { await postService.createPost(formData) } showToast('Post published', 'success') } } else if (type === 'reel') { if (mediaPreviews.length === 0 || mediaPreviews[0].type !== 'video') { setError('Select a video file for reel.') setSubmitting(false) return } const formData = new FormData() formData.append('video', mediaPreviews[0].file) formData.append('title', caption.trim() || `Reel for ${repo?.owner}/${repo?.name}`) formData.append('description', caption) if (repo) { formData.append('repoOwner', repo.owner) formData.append('repoName', repo.name) } if (hashtags.trim()) formData.append('hashtags', hashtags) // Add code snippet overlay data if present if (codeSnippets.length > 0) { formData.append('codeSnippets', JSON.stringify(codeSnippets)) } await reelService.createReel(formData) showToast('Reel published', 'success') } else if (type === 'story') { if (mediaPreviews.length === 0) { setError('Select image/video for story.') setSubmitting(false) return } const formData = new FormData() formData.append('media', mediaPreviews[0].file) formData.append('mediaType', mediaPreviews[0].type) formData.append('caption', caption) if (repo) { formData.append('repoOwner', repo.owner) formData.append('repoName', repo.name) } await storyService.createStory(formData) showToast('Story published', 'success') } else { // change_story if (!checkpointId.trim()) { setError('checkpointId is required for change story.') setSubmitting(false) return } if (!repo) { setError('Select a repository first.') setSubmitting(false) return } await repoService.createChangeStory(repo.owner, repo.name, { title: changeTitle, summary: content || caption, checkpointId: checkpointId.trim(), fromCheckpointId: fromCheckpointId.trim() || undefined, aitmProjectId: aitmProjectId.trim() || undefined, diffSummary: { added: Number(diffAdded || 0), removed: Number(diffRemoved || 0), modified: Number(diffModified || 0), }, changedFiles: changedFiles .split('\n') .map((line) => line.trim()) .filter(Boolean), }) showToast('Change story published', 'success') } // Clean up draft if exists if (currentDraftId) { await draftService.deleteDraft(currentDraftId).catch(() => {}) } if (repo) { router.push(buildRepoPath(repo.owner, repo.name)) } else { router.push('/feed') } } catch (err: unknown) { setError(getErrorMessage(err)) } finally { setSubmitting(false) } } const typeConfig = [ { key: 'post', label: 'Post', icon: ( ), }, { key: 'reel', label: 'Reel', icon: ( ), }, { key: 'story', label: 'Story', icon: ( ), }, { key: 'change_story', label: 'Change Story', icon: ( ), }, ] return (
    {/* Header */}

    Compose

    {lastSaved && ( Saved {lastSaved.toLocaleTimeString()} )}
    {/* Type Selector Tabs */}
    {typeConfig.map((tab) => ( ))}
    {/* Repository Selector */}
    {loadingRepos && (
    Loading repositories...
    )}
    {checkpointId && aitmProjectId && (

    AITM checkpoint linked

    Publishing from this composer will attach checkpoint {checkpointId} {' '}from project {aitmProjectId}.

    )} {/* Post Editor */} {type === 'post' && (
    {/* Markdown Toolbar */}
    {/* Content editor / preview */} {showPreview ? (
    ) : ( )}
    )} {/* Reel / Story Caption */} {(type === 'reel' || type === 'story') && (
    )} {/* Hashtag Input */} {(type === 'post' || type === 'reel') && (
    handleHashtagInput(e.target.value)} className="w-full rounded-lg border border-border bg-background px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="react, typescript, opensource (comma-separated)" /> {hashtagSuggestions.length > 0 && (
    {hashtagSuggestions.map((tag) => ( ))}
    )}
    )} {/* Code Snippet Editor (inline) */} {showSnippetEditor && ( setShowSnippetEditor(false)} repoOwner={repo?.owner} repoName={repo?.name} /> )} {/* Code Snippets List */} {codeSnippets.length > 0 && (
    {codeSnippets.map((snippet) => (
    ))}
    )} {/* Media Upload with Drag-and-Drop */} {(type === 'post' || type === 'reel' || type === 'story') && (
    {/* Drag and drop zone */}
    fileInputRef.current?.click()} className={`relative border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all ${ isDragging ? 'border-primary bg-primary/5' : 'border-border hover:border-primary/50 hover:bg-surface-secondary/50' }`} >

    Click to upload or drag and drop

    {type === 'reel' ? 'MP4, MOV, WebM' : 'PNG, JPG, GIF, MP4, MOV'}

    {/* Media previews */} {mediaPreviews.length > 0 && (
    {mediaPreviews.map((preview, index) => (
    {preview.type === 'image' ? ( {`Upload ) : (
    ))}
    )}
    )} {/* Change Story Fields */} {type === 'change_story' && (

    Change Story Details

    setChangeTitle(e.target.value)} className="w-full rounded-lg border border-border bg-background px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-primary" placeholder="Change story title" /> {/* AITM Project selector */}
    {/* Checkpoint selectors */}
    {aitmCheckpoints.length > 0 ? ( ) : ( setFromCheckpointId(e.target.value)} className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary" placeholder="fromCheckpointId" /> )}
    {aitmCheckpoints.length > 0 ? ( ) : ( setCheckpointId(e.target.value)} className="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary" placeholder="checkpointId *" /> )}
    {/* Auto-generate diff button */} {fromCheckpointId && checkpointId && aitmProjectId && ( )} {/* Diff stats */}
    + setDiffAdded(e.target.value)} className="w-full rounded-lg border border-border bg-background pl-7 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary" placeholder="added" />
    - setDiffRemoved(e.target.value)} className="w-full rounded-lg border border-border bg-background pl-7 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary" placeholder="removed" />
    ~ setDiffModified(e.target.value)} className="w-full rounded-lg border border-border bg-background pl-7 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary" placeholder="modified" />
    {/* Changed files */}