1143 lines
44 KiB
TypeScript
1143 lines
44 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import { useMutation, useQuery } from 'convex/react'
|
|
import { api } from '@/convex/_generated/api'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { Checkbox } from '@/components/ui/checkbox'
|
|
import { Slider } from '@/components/ui/slider'
|
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
|
import { Progress } from '@/components/ui/progress'
|
|
import { Separator } from '@/components/ui/separator'
|
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogFooter
|
|
} from '@/components/ui/dialog'
|
|
import {
|
|
Table,
|
|
TableBody,
|
|
TableCell,
|
|
TableHead,
|
|
TableHeader,
|
|
TableRow
|
|
} from '@/components/ui/table'
|
|
import { Textarea } from '@/components/ui/textarea'
|
|
import { Label } from '@/components/ui/label'
|
|
import {
|
|
Search,
|
|
Loader2,
|
|
ExternalLink,
|
|
Globe,
|
|
ChevronDown,
|
|
ChevronUp,
|
|
Settings,
|
|
Target,
|
|
AlertCircle,
|
|
BarChart3,
|
|
CheckCircle2,
|
|
Eye,
|
|
Plus,
|
|
X,
|
|
Users,
|
|
Copy
|
|
} from 'lucide-react'
|
|
import { useProject } from '@/components/project-context'
|
|
import type {
|
|
EnhancedProductAnalysis,
|
|
Opportunity,
|
|
PlatformConfig,
|
|
SearchStrategy,
|
|
SearchConfig
|
|
} from '@/lib/types'
|
|
import { estimateSearchTime } from '@/lib/query-generator'
|
|
|
|
const STRATEGY_INFO: Record<SearchStrategy, { name: string; description: string }> = {
|
|
'direct-keywords': { name: 'Direct Keywords', description: 'People looking for your product category' },
|
|
'problem-pain': { name: 'Problem/Pain', description: 'People experiencing problems you solve' },
|
|
'competitor-alternative': { name: 'Competitor Alternatives', description: 'People switching from competitors' },
|
|
'how-to': { name: 'How-To/Tutorials', description: 'People learning about solutions' },
|
|
'emotional-frustrated': { name: 'Frustration Posts', description: 'Emotional posts about pain points' },
|
|
'comparison': { name: 'Comparisons', description: '"X vs Y" comparison posts' },
|
|
'recommendation': { name: 'Recommendations', description: '"What do you use" requests' }
|
|
}
|
|
|
|
const STRATEGY_GROUPS: { title: string; description: string; strategies: SearchStrategy[] }[] = [
|
|
{
|
|
title: "High intent",
|
|
description: "People actively looking or comparing options.",
|
|
strategies: ["direct-keywords", "competitor-alternative", "comparison", "recommendation"],
|
|
},
|
|
{
|
|
title: "Problem-driven",
|
|
description: "Pain and frustration expressed in public threads.",
|
|
strategies: ["problem-pain", "emotional-frustrated"],
|
|
},
|
|
{
|
|
title: "Learning intent",
|
|
description: "Educational and how-to discovery signals.",
|
|
strategies: ["how-to"],
|
|
},
|
|
]
|
|
|
|
function ChannelLogo({ id }: { id: string }) {
|
|
const common = "h-4 w-4 text-foreground"
|
|
const wrapper = "flex h-7 w-7 items-center justify-center rounded-md border border-border/60 bg-background"
|
|
|
|
const icons: Record<string, JSX.Element> = {
|
|
reddit: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path
|
|
fill="currentColor"
|
|
d="M14.87 2.5a.75.75 0 0 0-.85.62l-.52 3.24a9.49 9.49 0 0 0-3.86.03L7.7 5.1a.75.75 0 1 0-1.4.53l1.95 5.18A5.98 5.98 0 0 0 6 12.25c0 2.7 2.69 4.88 6 4.88s6-2.18 6-4.88a5.98 5.98 0 0 0-2.17-1.46l1.3-5.1a.75.75 0 1 0-1.46-.37l-1.26 4.94a9.6 9.6 0 0 0-2.32-.28c-.6 0-1.18.06-1.73.17l.35-2.18a.75.75 0 0 0-.62-.85l-.22-.03 4.04-.63a.75.75 0 0 0 .62-.85Z"
|
|
/>
|
|
<circle cx="9" cy="12.7" r="1.1" fill="currentColor" />
|
|
<circle cx="15" cy="12.7" r="1.1" fill="currentColor" />
|
|
<path fill="currentColor" d="M8.7 15.4a6 6 0 0 0 6.6 0 .6.6 0 0 0-.7-1 4.8 4.8 0 0 1-5.2 0 .6.6 0 0 0-.7 1Z" />
|
|
</svg>
|
|
),
|
|
twitter: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path
|
|
fill="currentColor"
|
|
d="M17.5 3h3.1l-6.8 7.8L21 21h-5.6l-4.4-5.7L5.9 21H2.8l7.3-8.4L3 3h5.7l4 5.3L17.5 3Zm-1 16h1.7L7.6 4.9H5.8L16.5 19Z"
|
|
/>
|
|
</svg>
|
|
),
|
|
hackernews: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path fill="currentColor" d="M4 3h16v18H4V3Zm3.2 4.2h2l2.8 4.7 2.8-4.7h2l-3.8 6v3.6h-1.8V13l-4-5.8Z" />
|
|
</svg>
|
|
),
|
|
indiehackers: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path fill="currentColor" d="M4 4h16v4H4V4Zm0 6h16v4H4v-4Zm0 6h16v4H4v-4Z" />
|
|
</svg>
|
|
),
|
|
quora: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path
|
|
fill="currentColor"
|
|
d="M12 3.5a8.5 8.5 0 1 0 5.7 14.8l2 2.2a.8.8 0 1 0 1.2-1.1l-2.1-2.3A8.5 8.5 0 0 0 12 3.5Zm0 1.8a6.7 6.7 0 1 1-4.7 11.4 6.7 6.7 0 0 1 4.7-11.4Z"
|
|
/>
|
|
</svg>
|
|
),
|
|
stackoverflow: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path
|
|
fill="currentColor"
|
|
d="M17.9 21H7.4v-5.6h1.8v3.8h6.9v-3.8H17.9V21Zm-7.6-6.2.3-1.8 6.9 1.1-.3 1.8-6.9-1.1Zm1-3.7.7-1.7 6.4 2.7-.7 1.7-6.4-2.7Zm2-3.4 1.1-1.4 5.5 4.2-1.1 1.4-5.5-4.2Zm3.2-3.3 1.4-1.1 4.1 5.6-1.4 1.1-4.1-5.6Z"
|
|
/>
|
|
</svg>
|
|
),
|
|
linkedin: (
|
|
<svg viewBox="0 0 24 24" className={common} aria-hidden="true">
|
|
<path
|
|
fill="currentColor"
|
|
d="M5.2 8.2H2.6V21h2.6V8.2Zm-.1-4.7a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3ZM21 13.2c0-3.1-1.6-4.6-4-4.6-1.8 0-2.6 1-3.1 1.7V8.2h-2.6c.1 1.3 0 12.8 0 12.8h2.6v-7.1c0-.4 0-.8.1-1.1.3-.8 1-1.6 2.1-1.6 1.5 0 2.1 1.2 2.1 2.9V21H21v-7.8Z"
|
|
/>
|
|
</svg>
|
|
),
|
|
}
|
|
|
|
const icon = icons[id]
|
|
return (
|
|
<div className={wrapper}>
|
|
{icon || <Globe className={common} />}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
const GOAL_PRESETS: {
|
|
id: string
|
|
title: string
|
|
description: string
|
|
strategies: SearchStrategy[]
|
|
maxQueries: number
|
|
}[] = [
|
|
{
|
|
id: "high-intent",
|
|
title: "High-intent leads",
|
|
description: "Shortlist people actively searching to buy or switch.",
|
|
strategies: ["direct-keywords", "competitor-alternative", "comparison", "recommendation"],
|
|
maxQueries: 30,
|
|
},
|
|
{
|
|
id: "pain-first",
|
|
title: "Problem pain",
|
|
description: "Find people expressing frustration or blockers.",
|
|
strategies: ["problem-pain", "emotional-frustrated"],
|
|
maxQueries: 40,
|
|
},
|
|
{
|
|
id: "market-scan",
|
|
title: "Market scan",
|
|
description: "Broader sweep to map demand and platforms.",
|
|
strategies: ["direct-keywords", "problem-pain", "how-to", "recommendation"],
|
|
maxQueries: 50,
|
|
},
|
|
]
|
|
|
|
export default function OpportunitiesPage() {
|
|
const router = useRouter()
|
|
const { selectedProjectId } = useProject()
|
|
const upsertOpportunities = useMutation(api.opportunities.upsertBatch)
|
|
const updateOpportunity = useMutation(api.opportunities.updateStatus)
|
|
const createSearchJob = useMutation(api.searchJobs.create)
|
|
const [analysis, setAnalysis] = useState<EnhancedProductAnalysis | null>(null)
|
|
const [platforms, setPlatforms] = useState<PlatformConfig[]>([])
|
|
const [strategies, setStrategies] = useState<SearchStrategy[]>([
|
|
'direct-keywords',
|
|
'problem-pain',
|
|
'competitor-alternative'
|
|
])
|
|
const [maxQueries, setMaxQueries] = useState(50)
|
|
const [goalPreset, setGoalPreset] = useState<string>('high-intent')
|
|
const [isSearching, setIsSearching] = useState(false)
|
|
const [opportunities, setOpportunities] = useState<Opportunity[]>([])
|
|
const [generatedQueries, setGeneratedQueries] = useState<any[]>([])
|
|
const [showQueries, setShowQueries] = useState(false)
|
|
const [selectedOpportunity, setSelectedOpportunity] = useState<Opportunity | null>(null)
|
|
const [replyText, setReplyText] = useState('')
|
|
const [stats, setStats] = useState<any>(null)
|
|
const [searchError, setSearchError] = useState('')
|
|
const [missingSources, setMissingSources] = useState<any[]>([])
|
|
const [lastSearchConfig, setLastSearchConfig] = useState<SearchConfig | null>(null)
|
|
const [statusFilter, setStatusFilter] = useState('all')
|
|
const [intentFilter, setIntentFilter] = useState('all')
|
|
const [limit, setLimit] = useState(50)
|
|
const [statusInput, setStatusInput] = useState('new')
|
|
const [notesInput, setNotesInput] = useState('')
|
|
const [tagsInput, setTagsInput] = useState('')
|
|
const [showAdvanced, setShowAdvanced] = useState(false)
|
|
const [showSourceDialog, setShowSourceDialog] = useState(false)
|
|
const [customSourceName, setCustomSourceName] = useState('')
|
|
const [customSourceSite, setCustomSourceSite] = useState('')
|
|
const [customSourceTemplate, setCustomSourceTemplate] = useState('{site} {term} {intent}')
|
|
const planLoadedRef = useRef<string | null>(null)
|
|
const defaultPlatformsRef = useRef<PlatformConfig[] | null>(null)
|
|
|
|
const projects = useQuery(api.projects.getProjects)
|
|
const latestAnalysis = useQuery(
|
|
api.analyses.getLatestByProject,
|
|
selectedProjectId ? { projectId: selectedProjectId as any } : 'skip'
|
|
)
|
|
|
|
const savedOpportunities = useQuery(
|
|
api.opportunities.listByProject,
|
|
selectedProjectId
|
|
? {
|
|
projectId: selectedProjectId as any,
|
|
status: statusFilter === 'all' ? undefined : statusFilter,
|
|
intent: intentFilter === 'all' ? undefined : intentFilter,
|
|
limit,
|
|
}
|
|
: 'skip'
|
|
)
|
|
|
|
const displayOpportunities = useMemo(() => {
|
|
if (!savedOpportunities || savedOpportunities.length === 0) return opportunities
|
|
return savedOpportunities.map((opp: any) => ({
|
|
id: opp._id,
|
|
title: opp.title,
|
|
url: opp.url,
|
|
snippet: opp.snippet,
|
|
platform: opp.platform,
|
|
source: opp.platform,
|
|
relevanceScore: opp.relevanceScore,
|
|
emotionalIntensity: 'low',
|
|
intent: opp.intent,
|
|
matchedKeywords: opp.matchedKeywords,
|
|
matchedProblems: opp.matchedProblems,
|
|
suggestedApproach: opp.suggestedApproach,
|
|
softPitch: opp.softPitch,
|
|
status: opp.status,
|
|
notes: opp.notes,
|
|
tags: opp.tags,
|
|
})) as Opportunity[]
|
|
}, [savedOpportunities, opportunities])
|
|
|
|
const selectedSources = useQuery(
|
|
api.dataSources.getProjectDataSources,
|
|
selectedProjectId ? { projectId: selectedProjectId as any } : "skip"
|
|
)
|
|
const searchJobs = useQuery(
|
|
api.searchJobs.listByProject,
|
|
selectedProjectId ? { projectId: selectedProjectId as any } : "skip"
|
|
)
|
|
|
|
const selectedProject = projects?.find((project: any) => project._id === selectedProjectId)
|
|
const selectedSourceIds = selectedProject?.dorkingConfig?.selectedSourceIds || []
|
|
const activeSources = selectedSources?.filter((source: any) =>
|
|
selectedSourceIds.includes(source._id)
|
|
) || []
|
|
const enabledPlatforms = platforms.filter((platform) => platform.enabled)
|
|
const estimatedMinutes = estimateSearchTime(Math.max(maxQueries, 1), enabledPlatforms.map((platform) => platform.id))
|
|
|
|
useEffect(() => {
|
|
const stored = localStorage.getItem('productAnalysis')
|
|
if (stored) {
|
|
setAnalysis(JSON.parse(stored))
|
|
}
|
|
|
|
fetch('/api/opportunities')
|
|
.then(r => {
|
|
if (r.redirected) {
|
|
router.push('/auth?next=/opportunities')
|
|
return null
|
|
}
|
|
return r.json()
|
|
})
|
|
.then(data => {
|
|
if (data) {
|
|
setPlatforms((prev) => (prev.length > 0 ? prev : data.platforms))
|
|
defaultPlatformsRef.current = data.platforms
|
|
}
|
|
})
|
|
}, [router])
|
|
|
|
useEffect(() => {
|
|
if (!selectedProjectId) return
|
|
if (platforms.length === 0) return
|
|
if (planLoadedRef.current === selectedProjectId) return
|
|
|
|
const key = `searchPlan:${selectedProjectId}`
|
|
const stored = localStorage.getItem(key)
|
|
if (stored) {
|
|
try {
|
|
const parsed = JSON.parse(stored)
|
|
if (Array.isArray(parsed.strategies)) {
|
|
setStrategies(parsed.strategies)
|
|
}
|
|
if (typeof parsed.maxQueries === 'number') {
|
|
setMaxQueries(Math.min(Math.max(parsed.maxQueries, 10), 50))
|
|
}
|
|
if (typeof parsed.goalPreset === 'string') {
|
|
setGoalPreset(parsed.goalPreset)
|
|
}
|
|
if (Array.isArray(parsed.platforms)) {
|
|
setPlatforms(parsed.platforms)
|
|
} else if (Array.isArray(parsed.platformIds)) {
|
|
setPlatforms((prev) =>
|
|
prev.map((platform) => ({
|
|
...platform,
|
|
enabled: parsed.platformIds.includes(platform.id),
|
|
}))
|
|
)
|
|
}
|
|
} catch {
|
|
// Ignore invalid cached config.
|
|
}
|
|
} else if (defaultPlatformsRef.current) {
|
|
setStrategies(['direct-keywords', 'problem-pain', 'competitor-alternative'])
|
|
setMaxQueries(50)
|
|
setGoalPreset('high-intent')
|
|
setPlatforms(defaultPlatformsRef.current)
|
|
}
|
|
|
|
planLoadedRef.current = selectedProjectId
|
|
}, [selectedProjectId, platforms])
|
|
|
|
useEffect(() => {
|
|
if (!analysis && latestAnalysis) {
|
|
setAnalysis(latestAnalysis as any)
|
|
}
|
|
}, [analysis, latestAnalysis])
|
|
|
|
useEffect(() => {
|
|
if (!selectedProjectId) return
|
|
if (planLoadedRef.current !== selectedProjectId) return
|
|
|
|
const key = `searchPlan:${selectedProjectId}`
|
|
const payload = {
|
|
goalPreset,
|
|
strategies,
|
|
maxQueries,
|
|
platforms,
|
|
}
|
|
localStorage.setItem(key, JSON.stringify(payload))
|
|
}, [selectedProjectId, goalPreset, strategies, maxQueries, platforms])
|
|
|
|
useEffect(() => {
|
|
if (!analysis && latestAnalysis === null) {
|
|
router.push('/onboarding')
|
|
}
|
|
}, [analysis, latestAnalysis, router])
|
|
|
|
const togglePlatform = (platformId: string) => {
|
|
setPlatforms(prev => prev.map(p =>
|
|
p.id === platformId ? { ...p, enabled: !p.enabled } : p
|
|
))
|
|
}
|
|
|
|
const removeCustomSource = (platformId: string) => {
|
|
setPlatforms(prev => prev.filter((platform) => platform.id !== platformId))
|
|
}
|
|
|
|
const toggleStrategy = (strategy: SearchStrategy) => {
|
|
setStrategies(prev =>
|
|
prev.includes(strategy)
|
|
? prev.filter(s => s !== strategy)
|
|
: [...prev, strategy]
|
|
)
|
|
}
|
|
|
|
const applyGoalPreset = (presetId: string) => {
|
|
const preset = GOAL_PRESETS.find((item) => item.id === presetId)
|
|
if (!preset) return
|
|
setGoalPreset(preset.id)
|
|
setStrategies(preset.strategies)
|
|
setMaxQueries(preset.maxQueries)
|
|
}
|
|
|
|
const addCustomSource = () => {
|
|
const name = customSourceName.trim()
|
|
const site = customSourceSite.trim().replace(/^https?:\/\//, '').replace(/\/.*$/, '')
|
|
if (!name || !site) return
|
|
|
|
const idSeed = `${name}-${site}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
|
|
const customId = `custom-${idSeed}-${Date.now().toString(36)}`
|
|
|
|
setPlatforms((prev) => [
|
|
...prev,
|
|
{
|
|
id: customId,
|
|
name,
|
|
icon: 'Globe',
|
|
enabled: true,
|
|
searchTemplate: customSourceTemplate.trim() || '{site} {term} {intent}',
|
|
rateLimit: 20,
|
|
site,
|
|
custom: true,
|
|
},
|
|
])
|
|
|
|
setCustomSourceName('')
|
|
setCustomSourceSite('')
|
|
setCustomSourceTemplate('{site} {term} {intent}')
|
|
setShowSourceDialog(false)
|
|
}
|
|
|
|
const executeSearch = async (overrideConfig?: SearchConfig) => {
|
|
if (!analysis) return
|
|
if (!selectedProjectId) return
|
|
|
|
setIsSearching(true)
|
|
setOpportunities([])
|
|
setSearchError('')
|
|
|
|
try {
|
|
const config = overrideConfig ?? {
|
|
platforms: platforms.map((platform) => ({
|
|
...platform,
|
|
icon: platform.icon ?? "",
|
|
searchTemplate: platform.searchTemplate ?? "",
|
|
})),
|
|
strategies,
|
|
maxResults: Math.min(maxQueries, 50)
|
|
}
|
|
setLastSearchConfig(config as SearchConfig)
|
|
|
|
const jobId = await createSearchJob({
|
|
projectId: selectedProjectId as any,
|
|
config,
|
|
})
|
|
|
|
const response = await fetch('/api/opportunities', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ projectId: selectedProjectId, config, jobId })
|
|
})
|
|
|
|
if (response.redirected) {
|
|
router.push('/auth?next=/opportunities')
|
|
return
|
|
}
|
|
|
|
const responseText = await response.text()
|
|
const data = responseText ? JSON.parse(responseText) : null
|
|
|
|
if (!response.ok) {
|
|
throw new Error(data?.error || 'Failed to search for opportunities')
|
|
}
|
|
|
|
if (data?.success) {
|
|
const mapped = data.data.opportunities.map((opp: Opportunity) => ({
|
|
...opp,
|
|
status: 'new',
|
|
}))
|
|
setOpportunities(mapped)
|
|
setGeneratedQueries(data.data.queries)
|
|
setStats(data.data.stats)
|
|
setMissingSources(data.data.missingSources || [])
|
|
|
|
await upsertOpportunities({
|
|
projectId: selectedProjectId as any,
|
|
analysisId: latestAnalysis?._id,
|
|
opportunities: mapped.map((opp: Opportunity) => ({
|
|
url: opp.url,
|
|
platform: opp.platform,
|
|
title: opp.title,
|
|
snippet: opp.snippet,
|
|
relevanceScore: opp.relevanceScore,
|
|
intent: opp.intent,
|
|
suggestedApproach: opp.suggestedApproach,
|
|
matchedKeywords: opp.matchedKeywords,
|
|
matchedProblems: opp.matchedProblems,
|
|
softPitch: opp.softPitch,
|
|
})),
|
|
})
|
|
} else {
|
|
throw new Error('Search returned no data')
|
|
}
|
|
} catch (error: any) {
|
|
console.error('Search error:', error)
|
|
setSearchError(error?.message || 'Search failed. Please try again.')
|
|
} finally {
|
|
setIsSearching(false)
|
|
}
|
|
}
|
|
|
|
const generateReply = (opp: Opportunity) => {
|
|
const template = opp.softPitch
|
|
? `Hey, I saw your post about ${opp.matchedProblems[0] || 'your challenge'}. We faced something similar and ended up building ${analysis?.productName} specifically for this. Happy to share what worked for us.`
|
|
: `Hi! I noticed you're looking for solutions to ${opp.matchedProblems[0]}. I work on ${analysis?.productName} that helps teams with this - specifically ${opp.matchedKeywords.slice(0, 2).join(' and ')}. Would love to show you how it works.`
|
|
setReplyText(template)
|
|
}
|
|
|
|
const getIntentIcon = (intent: string) => {
|
|
switch (intent) {
|
|
case 'frustrated': return <AlertCircle className="h-4 w-4 text-red-400" />
|
|
case 'comparing': return <BarChart3 className="h-4 w-4 text-amber-400" />
|
|
case 'learning': return <Users className="h-4 w-4 text-blue-400" />
|
|
default: return <Target className="h-4 w-4 text-muted-foreground" />
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (selectedOpportunity) {
|
|
setStatusInput(selectedOpportunity.status || 'new')
|
|
setNotesInput(selectedOpportunity.notes || '')
|
|
setTagsInput(selectedOpportunity.tags?.join(', ') || '')
|
|
}
|
|
}, [selectedOpportunity])
|
|
|
|
const handleSaveOpportunity = async () => {
|
|
if (!selectedOpportunity?.id) return
|
|
|
|
const tags = tagsInput
|
|
.split(',')
|
|
.map((tag) => tag.trim())
|
|
.filter(Boolean)
|
|
|
|
await updateOpportunity({
|
|
id: selectedOpportunity.id as any,
|
|
status: statusInput,
|
|
notes: notesInput || undefined,
|
|
tags: tags.length > 0 ? tags : undefined,
|
|
})
|
|
}
|
|
|
|
if (!analysis) return null
|
|
|
|
const latestJob = searchJobs && searchJobs.length > 0 ? searchJobs[0] : null
|
|
|
|
return (
|
|
<div className="flex h-screen">
|
|
{/* Sidebar */}
|
|
<div className="w-96 border-r border-border bg-card flex flex-col">
|
|
<div className="p-4 border-b border-border space-y-1">
|
|
<div className="flex items-center justify-between">
|
|
<h2 className="font-semibold flex items-center gap-2">
|
|
<Target className="h-5 w-5" />
|
|
Search Setup
|
|
</h2>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={() => setShowAdvanced(true)}
|
|
aria-label="Advanced settings"
|
|
>
|
|
<Settings className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
<p className="text-xs text-muted-foreground">
|
|
Pick a goal, tune sources, then run the scan.
|
|
</p>
|
|
</div>
|
|
|
|
<ScrollArea className="flex-1 p-4 space-y-6">
|
|
{/* Platforms */}
|
|
<div className="space-y-3">
|
|
<Label className="text-sm font-medium uppercase text-muted-foreground">Sources</Label>
|
|
<div className="grid gap-2">
|
|
{platforms.map(platform => {
|
|
const isEnabled = platform.enabled
|
|
return (
|
|
<button
|
|
key={platform.id}
|
|
type="button"
|
|
onClick={() => togglePlatform(platform.id)}
|
|
className={`flex items-center justify-between rounded-lg border px-3 py-2 text-left transition ${
|
|
isEnabled
|
|
? "border-foreground/50 bg-muted/50"
|
|
: "border-border/60 hover:border-foreground/30 hover:bg-muted/40"
|
|
}`}
|
|
>
|
|
<div className="flex items-center gap-2">
|
|
<ChannelLogo id={platform.id} />
|
|
<div>
|
|
<div className="text-sm font-medium">{platform.name}</div>
|
|
<div className="text-xs text-muted-foreground">
|
|
{isEnabled ? "Included" : "Excluded"}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{platform.custom && (
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={(event) => {
|
|
event.stopPropagation()
|
|
removeCustomSource(platform.id)
|
|
}}
|
|
className="h-7 w-7"
|
|
>
|
|
<X className="h-4 w-4" />
|
|
</Button>
|
|
)}
|
|
<Checkbox checked={isEnabled} />
|
|
</div>
|
|
</button>
|
|
)
|
|
})}
|
|
</div>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setShowSourceDialog(true)}
|
|
className="w-full"
|
|
>
|
|
<Plus className="mr-2 h-4 w-4" />
|
|
Add source
|
|
</Button>
|
|
</div>
|
|
|
|
<Separator />
|
|
|
|
</ScrollArea>
|
|
|
|
<div className="p-4 border-t border-border space-y-2">
|
|
<div className="space-y-2">
|
|
<Label className="text-sm font-medium uppercase text-muted-foreground">Search Volume</Label>
|
|
<div className="space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-xs text-muted-foreground">Max Queries</span>
|
|
<span className="text-xs text-muted-foreground">{maxQueries}</span>
|
|
</div>
|
|
<Slider
|
|
value={[maxQueries]}
|
|
onValueChange={([v]) => setMaxQueries(v)}
|
|
min={10}
|
|
max={50}
|
|
step={5}
|
|
/>
|
|
<div className="text-xs text-muted-foreground">
|
|
Up to {maxQueries} queries · est. {estimatedMinutes} min
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<Button
|
|
onClick={() => executeSearch()}
|
|
disabled={
|
|
isSearching ||
|
|
platforms.filter(p => p.enabled).length === 0 ||
|
|
selectedSourceIds.length === 0
|
|
}
|
|
className="w-full"
|
|
>
|
|
{isSearching ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Searching...</> : <><Search className="mr-2 h-4 w-4" /> Run Search</>}
|
|
</Button>
|
|
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
|
|
<span>{enabledPlatforms.length || 0} sources</span>
|
|
<span>·</span>
|
|
<span>{strategies.length} triggers</span>
|
|
<span>·</span>
|
|
<span>max {maxQueries} queries</span>
|
|
</div>
|
|
{platforms.filter(p => p.enabled).length === 0 && (
|
|
<p className="text-xs text-muted-foreground">Select at least one source to search.</p>
|
|
)}
|
|
{selectedSourceIds.length === 0 && (
|
|
<p className="text-xs text-muted-foreground">Select data sources to build search context.</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<Dialog open={showAdvanced} onOpenChange={setShowAdvanced}>
|
|
<DialogContent className="max-w-xl max-h-[80vh] overflow-hidden">
|
|
<DialogHeader>
|
|
<DialogTitle>Advanced settings</DialogTitle>
|
|
<DialogDescription>Fine-tune goals and triggers for this search.</DialogDescription>
|
|
</DialogHeader>
|
|
<ScrollArea className="max-h-[60vh] pr-4">
|
|
<div className="space-y-6">
|
|
<div className="space-y-3">
|
|
<Label className="text-sm font-medium uppercase text-muted-foreground">Search Goal</Label>
|
|
<div className="grid gap-2">
|
|
{GOAL_PRESETS.map((preset) => (
|
|
<button
|
|
key={preset.id}
|
|
type="button"
|
|
onClick={() => applyGoalPreset(preset.id)}
|
|
className={`rounded-lg border px-3 py-2 text-left transition ${
|
|
goalPreset === preset.id
|
|
? "border-foreground/60 bg-muted/50"
|
|
: "border-border/60 hover:border-foreground/30 hover:bg-muted/40"
|
|
}`}
|
|
>
|
|
<div className="text-sm font-semibold">{preset.title}</div>
|
|
<div className="text-xs text-muted-foreground">{preset.description}</div>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-4">
|
|
<Label className="text-sm font-medium uppercase text-muted-foreground">Triggers</Label>
|
|
{STRATEGY_GROUPS.map((group) => (
|
|
<div key={group.title} className="space-y-2">
|
|
<div>
|
|
<div className="text-sm font-semibold">{group.title}</div>
|
|
<div className="text-xs text-muted-foreground">{group.description}</div>
|
|
</div>
|
|
<div className="space-y-2">
|
|
{group.strategies.map((strategy) => (
|
|
<div key={strategy} className="flex items-start gap-2 rounded-md border border-border/60 px-2 py-2">
|
|
<Checkbox
|
|
id={strategy}
|
|
checked={strategies.includes(strategy)}
|
|
onCheckedChange={() => toggleStrategy(strategy)}
|
|
/>
|
|
<div className="flex-1">
|
|
<Label htmlFor={strategy} className="cursor-pointer text-sm font-medium">
|
|
{STRATEGY_INFO[strategy].name}
|
|
</Label>
|
|
<p className="text-xs text-muted-foreground">{STRATEGY_INFO[strategy].description}</p>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</ScrollArea>
|
|
</DialogContent>
|
|
</Dialog>
|
|
|
|
<Dialog open={showSourceDialog} onOpenChange={setShowSourceDialog}>
|
|
<DialogContent className="max-w-lg">
|
|
<DialogHeader>
|
|
<DialogTitle>Add source</DialogTitle>
|
|
<DialogDescription>Add a custom site to search.</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="space-y-4">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="custom-source-name">Source name</Label>
|
|
<input
|
|
id="custom-source-name"
|
|
value={customSourceName}
|
|
onChange={(event) => setCustomSourceName(event.target.value)}
|
|
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
|
|
placeholder="e.g. Product Hunt"
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="custom-source-site">Website domain</Label>
|
|
<input
|
|
id="custom-source-site"
|
|
value={customSourceSite}
|
|
onChange={(event) => setCustomSourceSite(event.target.value)}
|
|
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
|
|
placeholder="producthunt.com"
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="custom-source-template">Search template</Label>
|
|
<Textarea
|
|
id="custom-source-template"
|
|
value={customSourceTemplate}
|
|
onChange={(event) => setCustomSourceTemplate(event.target.value)}
|
|
rows={3}
|
|
placeholder="{site} {term} {intent}"
|
|
/>
|
|
<p className="text-xs text-muted-foreground">
|
|
Use {site}, {term}, and {intent}.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<DialogFooter>
|
|
<Button variant="ghost" onClick={() => setShowSourceDialog(false)}>
|
|
Cancel
|
|
</Button>
|
|
<Button onClick={addCustomSource} disabled={!customSourceName.trim() || !customSourceSite.trim()}>
|
|
Add source
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
|
|
{/* Main Content */}
|
|
<div className="flex-1 overflow-auto p-6">
|
|
<div className="max-w-4xl mx-auto space-y-6">
|
|
{/* Header */}
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<div>
|
|
<h1 className="text-2xl font-bold">Search Results</h1>
|
|
<p className="text-muted-foreground">Discover potential customers for {analysis.productName}</p>
|
|
</div>
|
|
{stats && (
|
|
<div className="flex gap-4 text-sm">
|
|
<div className="text-center">
|
|
<div className="font-semibold">{stats.opportunitiesFound}</div>
|
|
<div className="text-muted-foreground">Found</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
|
|
<Badge variant="outline">Goal: {GOAL_PRESETS.find((preset) => preset.id === goalPreset)?.title || "Custom"}</Badge>
|
|
<Badge variant="outline">Max queries: {maxQueries}</Badge>
|
|
</div>
|
|
{latestJob && (latestJob.status === "running" || latestJob.status === "pending") && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-sm">Search running</CardTitle>
|
|
<CardDescription>
|
|
Current job: {latestJob.status}
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-2">
|
|
<Progress value={typeof latestJob.progress === "number" ? latestJob.progress : 10} />
|
|
<div className="text-xs text-muted-foreground">
|
|
{typeof latestJob.progress === "number" ? `${latestJob.progress}% complete` : "Starting..."}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
{latestJob && latestJob.status === "failed" && (
|
|
<Alert variant="destructive">
|
|
<AlertDescription>
|
|
Search failed: {latestJob.error || "Unknown error"}.{" "}
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="ml-2"
|
|
onClick={() => executeSearch((latestJob.config as SearchConfig) || lastSearchConfig || undefined)}
|
|
>
|
|
Retry
|
|
</Button>
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
{searchError && (
|
|
<Alert variant="destructive">
|
|
<AlertDescription>
|
|
{searchError}
|
|
{searchError.includes('SERPER_API_KEY') && (
|
|
<span className="block mt-2 text-xs text-muted-foreground">
|
|
Add `SERPER_API_KEY` to your environment and restart the app to enable search.
|
|
</span>
|
|
)}
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
|
|
{/* Active Sources */}
|
|
{activeSources.length > 0 && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-sm">Inputs in use</CardTitle>
|
|
<CardDescription>
|
|
Sources selected for this project will drive opportunity search.
|
|
</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="flex flex-wrap gap-2">
|
|
{activeSources.map((source: any) => (
|
|
<Badge key={source._id} variant="secondary">
|
|
{source.name || source.url}
|
|
</Badge>
|
|
))}
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{selectedSources && selectedSourceIds.length === 0 && (
|
|
<Alert variant="destructive">
|
|
<AlertDescription>
|
|
No data sources selected. Add and select sources to generate opportunities.
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
|
|
{missingSources.length > 0 && (
|
|
<Alert>
|
|
<AlertDescription>
|
|
Some selected sources don't have analysis yet:{" "}
|
|
{missingSources
|
|
.map((missing) =>
|
|
activeSources.find((source: any) => source._id === missing.sourceId)?.name ||
|
|
activeSources.find((source: any) => source._id === missing.sourceId)?.url ||
|
|
missing.sourceId
|
|
)
|
|
.join(", ")}
|
|
. Run onboarding or re-analyze them for best results.
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
|
|
{/* Generated Queries */}
|
|
{generatedQueries.length > 0 && (
|
|
<Collapsible open={showQueries} onOpenChange={setShowQueries}>
|
|
<Card>
|
|
<CollapsibleTrigger asChild>
|
|
<CardHeader className="cursor-pointer">
|
|
<div className="flex items-center justify-between">
|
|
<CardTitle className="text-sm">Search Queries ({generatedQueries.length})</CardTitle>
|
|
{showQueries ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
|
</div>
|
|
</CardHeader>
|
|
</CollapsibleTrigger>
|
|
<CollapsibleContent>
|
|
<CardContent>
|
|
<div className="space-y-1 max-h-48 overflow-auto text-xs font-mono">
|
|
{generatedQueries.slice(0, 20).map((q, i) => (
|
|
<div key={i} className="bg-muted px-2 py-1 rounded">{q.query}</div>
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</CollapsibleContent>
|
|
</Card>
|
|
</Collapsible>
|
|
)}
|
|
|
|
{/* Results Table */}
|
|
{displayOpportunities.length > 0 ? (
|
|
<Card>
|
|
<div className="flex flex-wrap items-center gap-3 border-b border-border p-4">
|
|
<div className="flex items-center gap-2">
|
|
<Label className="text-xs text-muted-foreground">Lead Status</Label>
|
|
<select
|
|
value={statusFilter}
|
|
onChange={(e) => setStatusFilter(e.target.value)}
|
|
className="h-8 rounded-md border border-input bg-background px-2 text-xs"
|
|
>
|
|
<option value="all">All</option>
|
|
<option value="new">New</option>
|
|
<option value="viewed">Viewed</option>
|
|
<option value="contacted">Contacted</option>
|
|
<option value="responded">Responded</option>
|
|
<option value="converted">Converted</option>
|
|
<option value="ignored">Ignored</option>
|
|
</select>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<Label className="text-xs text-muted-foreground">Buyer Intent</Label>
|
|
<select
|
|
value={intentFilter}
|
|
onChange={(e) => setIntentFilter(e.target.value)}
|
|
className="h-8 rounded-md border border-input bg-background px-2 text-xs"
|
|
>
|
|
<option value="all">All</option>
|
|
<option value="frustrated">Frustrated</option>
|
|
<option value="comparing">Comparing</option>
|
|
<option value="learning">Learning</option>
|
|
<option value="recommending">Recommending</option>
|
|
<option value="looking">Looking</option>
|
|
</select>
|
|
</div>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setLimit((prev) => prev + 50)}
|
|
>
|
|
Load more
|
|
</Button>
|
|
</div>
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead>Source</TableHead>
|
|
<TableHead>Buyer Intent</TableHead>
|
|
<TableHead>Lead Status</TableHead>
|
|
<TableHead className="w-1/2">Post</TableHead>
|
|
<TableHead>Actions</TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{displayOpportunities.slice(0, limit).map((opp) => (
|
|
<TableRow key={opp.id}>
|
|
<TableCell><Badge variant="outline">{opp.platform}</Badge></TableCell>
|
|
<TableCell>
|
|
<div className="flex items-center gap-2">
|
|
{getIntentIcon(opp.intent)}
|
|
<span className="capitalize text-sm">{opp.intent}</span>
|
|
</div>
|
|
</TableCell>
|
|
<TableCell>
|
|
<Badge variant="secondary" className="capitalize">
|
|
{opp.status || 'new'}
|
|
</Badge>
|
|
</TableCell>
|
|
<TableCell>
|
|
<p className="font-medium line-clamp-1">{opp.title}</p>
|
|
<p className="text-sm text-muted-foreground line-clamp-2">{opp.snippet}</p>
|
|
</TableCell>
|
|
<TableCell>
|
|
<div className="flex gap-1">
|
|
<Button variant="ghost" size="sm" onClick={() => setSelectedOpportunity(opp)}>
|
|
<Eye className="h-4 w-4" />
|
|
</Button>
|
|
<Button variant="ghost" size="sm" onClick={() => window.open(opp.url, '_blank')}>
|
|
<ExternalLink className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
</Card>
|
|
) : isSearching ? (
|
|
<Card className="p-12 text-center">
|
|
<Loader2 className="mx-auto h-12 w-12 text-muted-foreground/50 mb-4 animate-spin" />
|
|
<h3 className="text-lg font-medium">Searching...</h3>
|
|
<p className="text-muted-foreground">Scanning platforms for opportunities</p>
|
|
</Card>
|
|
) : (
|
|
<Card className="p-12 text-center">
|
|
<Search className="mx-auto h-12 w-12 text-muted-foreground/50 mb-4" />
|
|
<h3 className="text-lg font-medium">Ready to Search</h3>
|
|
<p className="text-muted-foreground">Select sources and triggers, then click Run Search</p>
|
|
</Card>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Detail Dialog */}
|
|
<Dialog open={!!selectedOpportunity} onOpenChange={() => setSelectedOpportunity(null)}>
|
|
<DialogContent className="max-w-2xl">
|
|
{selectedOpportunity && (
|
|
<>
|
|
<DialogHeader>
|
|
<div className="flex items-center gap-2">
|
|
<Badge variant="outline">{selectedOpportunity.platform}</Badge>
|
|
<Badge variant="secondary" className="capitalize">{selectedOpportunity.intent}</Badge>
|
|
</div>
|
|
<DialogTitle className="text-lg pt-2">{selectedOpportunity.title}</DialogTitle>
|
|
<DialogDescription>{selectedOpportunity.snippet}</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<div className="space-y-4">
|
|
<div className="grid gap-4 md:grid-cols-2">
|
|
<div className="space-y-2">
|
|
<Label>Lead Status</Label>
|
|
<select
|
|
value={statusInput}
|
|
onChange={(e) => setStatusInput(e.target.value)}
|
|
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
|
|
>
|
|
<option value="new">New</option>
|
|
<option value="viewed">Viewed</option>
|
|
<option value="contacted">Contacted</option>
|
|
<option value="responded">Responded</option>
|
|
<option value="converted">Converted</option>
|
|
<option value="ignored">Ignored</option>
|
|
</select>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label>Tags (comma separated)</Label>
|
|
<input
|
|
value={tagsInput}
|
|
onChange={(e) => setTagsInput(e.target.value)}
|
|
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
|
|
placeholder="reddit, high-intent"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label>Notes</Label>
|
|
<Textarea
|
|
value={notesInput}
|
|
onChange={(e) => setNotesInput(e.target.value)}
|
|
placeholder="Add notes about this lead..."
|
|
rows={3}
|
|
/>
|
|
</div>
|
|
|
|
{selectedOpportunity.matchedKeywords.length > 0 && (
|
|
<div>
|
|
<Label className="text-sm text-muted-foreground">Keyword Matches</Label>
|
|
<div className="flex flex-wrap gap-2 mt-1">
|
|
{selectedOpportunity.matchedKeywords.map((kw, i) => (
|
|
<Badge key={i} variant="secondary">{kw}</Badge>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<div className="bg-muted p-4 rounded-lg">
|
|
<Label className="text-sm text-muted-foreground">Suggested Outreach</Label>
|
|
<p className="text-sm mt-1">{selectedOpportunity.suggestedApproach}</p>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<Label>Draft Reply</Label>
|
|
<div className="flex gap-2">
|
|
<Button variant="outline" size="sm" onClick={() => generateReply(selectedOpportunity)}>
|
|
<Zap className="h-3 w-3 mr-1" /> Generate
|
|
</Button>
|
|
{replyText && (
|
|
<Button variant="ghost" size="sm" onClick={() => navigator.clipboard.writeText(replyText)}>
|
|
<Copy className="h-3 w-3 mr-1" /> Copy
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<Textarea value={replyText} onChange={(e) => setReplyText(e.target.value)} placeholder="Click Generate to create a reply..." rows={4} />
|
|
</div>
|
|
</div>
|
|
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={() => window.open(selectedOpportunity.url, '_blank')}>
|
|
<ExternalLink className="h-4 w-4 mr-2" /> View Post
|
|
</Button>
|
|
<Button onClick={async () => {
|
|
await handleSaveOpportunity()
|
|
setSelectedOpportunity(null)
|
|
}}>
|
|
<CheckCircle2 className="h-4 w-4 mr-2" /> Save Updates
|
|
</Button>
|
|
</DialogFooter>
|
|
</>
|
|
)}
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
)
|
|
}
|