The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
v2.6.0 — Collab overhaul, route travel times, chat & notes redesign
Maurice068b90ed72b6
diff --git a/client/package.json b/client/package.jsonindex 28bf4d280..5420606f4 100644--- a/client/package.json+++ b/client/package.json@@ -1,6 +1,6 @@{"name": "nomad-client",- "version": "2.5.7",+ "version": "2.6.0","private": true,"type": "module","scripts": {diff --git a/client/src/api/client.js b/client/src/api/client.jsindex 6920b87ee..7b4477765 100644--- a/client/src/api/client.js+++ b/client/src/api/client.js@@ -204,6 +204,8 @@ export const collabApi = {createNote: (tripId, data) => apiClient.post(`/trips/${tripId}/collab/notes`, data).then(r => r.data),updateNote: (tripId, id, data) => apiClient.put(`/trips/${tripId}/collab/notes/${id}`, data).then(r => r.data),deleteNote: (tripId, id) => apiClient.delete(`/trips/${tripId}/collab/notes/${id}`).then(r => r.data),+ uploadNoteFile: (tripId, noteId, formData) => apiClient.post(`/trips/${tripId}/collab/notes/${noteId}/files`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),+ deleteNoteFile: (tripId, noteId, fileId) => apiClient.delete(`/trips/${tripId}/collab/notes/${noteId}/files/${fileId}`).then(r => r.data),// PollsgetPolls: (tripId) => apiClient.get(`/trips/${tripId}/collab/polls`).then(r => r.data),createPoll: (tripId, data) => apiClient.post(`/trips/${tripId}/collab/polls`, data).then(r => r.data),@@ -214,6 +216,8 @@ export const collabApi = {getMessages: (tripId, before) => apiClient.get(`/trips/${tripId}/collab/messages${before ? `?before=${before}` : ''}`).then(r => r.data),sendMessage: (tripId, data) => apiClient.post(`/trips/${tripId}/collab/messages`, data).then(r => r.data),deleteMessage: (tripId, id) => apiClient.delete(`/trips/${tripId}/collab/messages/${id}`).then(r => r.data),+ reactMessage: (tripId, id, emoji) => apiClient.post(`/trips/${tripId}/collab/messages/${id}/react`, { emoji }).then(r => r.data),+ linkPreview: (tripId, url) => apiClient.get(`/trips/${tripId}/collab/link-preview?url=${encodeURIComponent(url)}`).then(r => r.data),}export const backupApi = {diff --git a/client/src/components/Admin/AddonManager.jsx b/client/src/components/Admin/AddonManager.jsxindex 3f9144839..82a82a4ff 100644--- a/client/src/components/Admin/AddonManager.jsx+++ b/client/src/components/Admin/AddonManager.jsx@@ -118,7 +118,7 @@ export default function AddonManager() {}function AddonRow({ addon, onToggle, t }) {- const isComingSoon = addon.id === 'collab'+ const isComingSoon = falsereturn (<div className="flex items-center gap-4 px-6 py-4 border-b transition-colors hover:opacity-95" style={{ borderColor: 'var(--border-secondary)', opacity: isComingSoon ? 0.5 : 1, pointerEvents: isComingSoon ? 'none' : 'auto' }}>{/* Icon */}diff --git a/client/src/components/Collab/CollabChat.jsx b/client/src/components/Collab/CollabChat.jsxindex 78b22e9ee..45c2efd39 100644--- a/client/src/components/Collab/CollabChat.jsx+++ b/client/src/components/Collab/CollabChat.jsx@@ -1,68 +1,328 @@import React, { useState, useEffect, useRef, useCallback } from 'react'-import { Send, Trash2, Reply, ChevronUp, MessageCircle } from 'lucide-react'+import ReactDOM from 'react-dom'+import { ArrowUp, Trash2, Reply, ChevronUp, MessageCircle, Smile, X } from 'lucide-react'import { collabApi } from '../../api/client'+import { useSettingsStore } from '../../store/settingsStore'import { addListener, removeListener } from '../../api/websocket'import { useTranslation } from '../../i18n'-/* ───────── relative timestamp ───────── */-function formatRelativeTime(isoString, t) {- const now = Date.now()- const then = new Date(isoString).getTime()- const diff = now - then-- const seconds = Math.floor(diff / 1000)- const minutes = Math.floor(seconds / 60)- const hours = Math.floor(minutes / 60)-- if (seconds < 60) return t('collab.chat.justNow')- if (minutes < 60) return t('collab.chat.minutesAgo', { n: minutes })- if (hours < 24) return t('collab.chat.hoursAgo', { n: hours })-- const d = new Date(isoString)- const today = new Date()- const yesterday = new Date()- yesterday.setDate(today.getDate() - 1)-- if (- d.getDate() === yesterday.getDate() &&- d.getMonth() === yesterday.getMonth() &&- d.getFullYear() === yesterday.getFullYear()- ) {- const hh = String(d.getHours()).padStart(2, '0')- const mm = String(d.getMinutes()).padStart(2, '0')- return `yesterday ${hh}:${mm}`+// ── Twemoji helper (Apple-style emojis via CDN) ──+function emojiToCodepoint(emoji) {+ const codepoints = []+ for (const c of emoji) {+ const cp = c.codePointAt(0)+ if (cp !== 0xfe0f) codepoints.push(cp.toString(16)) // skip variation selector}+ return codepoints.join('-')+}++function TwemojiImg({ emoji, size = 20, style = {} }) {+ const cp = emojiToCodepoint(emoji)+ const [failed, setFailed] = useState(false)++ if (failed) {+ return <span style={{ fontSize: size, lineHeight: 1, display: 'inline-block', verticalAlign: 'middle', ...style }}>{emoji}</span>+ }++ return (+ <img+ src={`https://cdn.jsdelivr.net/gh/twitter/[email protected]/assets/72x72/${cp}.png`}+ alt={emoji}+ draggable={false}+ style={{ width: size, height: size, display: 'inline-block', verticalAlign: 'middle', ...style }}+ onError={() => setFailed(true)}+ />+ )+}++const EMOJI_CATEGORIES = {+ 'Smileys': ['😀','😂','🥹','😍','🤩','😎','🥳','😭','🤔','👀','🙈','🫠','😴','🤯','🥺','😤','💀','👻','🫡','🤝'],+ 'Reactions': ['❤️','🔥','👍','👎','👏','🎉','💯','✨','⭐','💪','🙏','😱','😂','💖','💕','🤞','✅','❌','⚡','🏆'],+ 'Travel': ['✈️','🏖️','🗺️','🧳','🏔️','🌅','🌴','🚗','🚂','🛳️','🏨','🍽️','🍕','🍹','📸','🎒','⛱️','🌍','🗼','🎌'],+}++// SQLite stores UTC without 'Z' suffix — append it so JS parses as UTC+function parseUTC(s) { return new Date(s && !s.endsWith('Z') ? s + 'Z' : s) }++function formatTime(isoString, is12h) {+ const d = parseUTC(isoString)+ const h = d.getHours()+ const mm = String(d.getMinutes()).padStart(2, '0')+ if (is12h) {+ const period = h >= 12 ? 'PM' : 'AM'+ const h12 = h === 0 ? 12 : h > 12 ? h - 12 : h+ return `${h12}:${mm} ${period}`+ }+ return `${String(h).padStart(2, '0')}:${mm}`+}++function formatDateSeparator(isoString, t) {+ const d = parseUTC(isoString)+ const now = new Date()+ const yesterday = new Date(); yesterday.setDate(now.getDate() - 1)++ if (d.toDateString() === now.toDateString()) return t('collab.chat.today') || 'Today'+ if (d.toDateString() === yesterday.toDateString()) return t('collab.chat.yesterday') || 'Yesterday'++ return d.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' })+}++function shouldShowDateSeparator(msg, prevMsg) {+ if (!prevMsg) return true+ const d1 = parseUTC(msg.created_at).toDateString()+ const d2 = parseUTC(prevMsg.created_at).toDateString()+ return d1 !== d2+}++/* ── Emoji Picker ── */+function EmojiPicker({ onSelect, onClose, anchorRef, containerRef }) {+ const [cat, setCat] = useState(Object.keys(EMOJI_CATEGORIES)[0])+ const ref = useRef(null)++ const getPos = () => {+ const container = containerRef?.current+ const anchor = anchorRef?.current+ if (container && anchor) {+ const cRect = container.getBoundingClientRect()+ const aRect = anchor.getBoundingClientRect()+ return { bottom: window.innerHeight - aRect.top + 16, left: cRect.left + cRect.width / 2 - 140 }+ }+ return { bottom: 80, left: 0 }+ }+ const pos = getPos()++ useEffect(() => {+ const close = (e) => {+ if (ref.current && ref.current.contains(e.target)) return+ if (anchorRef?.current && anchorRef.current.contains(e.target)) return+ onClose()+ }+ document.addEventListener('mousedown', close)+ return () => document.removeEventListener('mousedown', close)+ }, [onClose, anchorRef])++ return ReactDOM.createPortal(+ <div ref={ref} style={{+ position: 'fixed', bottom: pos.bottom, left: pos.left, zIndex: 10000,+ background: 'var(--bg-card)', border: '1px solid var(--border-faint)', borderRadius: 16,+ boxShadow: '0 8px 32px rgba(0,0,0,0.18)', width: 280, overflow: 'hidden',+ }}>+ {/* Category tabs */}+ <div style={{ display: 'flex', borderBottom: '1px solid var(--border-faint)', padding: '6px 8px', gap: 2 }}>+ {Object.keys(EMOJI_CATEGORIES).map(c => (+ <button key={c} onClick={() => setCat(c)} style={{+ flex: 1, padding: '4px 0', borderRadius: 6, border: 'none', cursor: 'pointer',+ background: cat === c ? 'var(--bg-hover)' : 'transparent',+ color: 'var(--text-primary)', fontSize: 10, fontWeight: 600, fontFamily: 'inherit',+ }}>+ {c}+ </button>+ ))}+ </div>+ {/* Emoji grid */}+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 2, padding: 8 }}>+ {EMOJI_CATEGORIES[cat].map((emoji, i) => (+ <button key={i} onClick={() => onSelect(emoji)} style={{+ width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center',+ background: 'none', border: 'none', cursor: 'pointer', borderRadius: 6,+ padding: 2, transition: 'transform 0.1s',+ }}+ onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.transform = 'scale(1.2)' }}+ onMouseLeave={e => { e.currentTarget.style.background = 'none'; e.currentTarget.style.transform = 'scale(1)' }}+ >+ <TwemojiImg emoji={emoji} size={20} />+ </button>+ ))}+ </div>+ </div>,+ document.body+ )+}++/* ── Reaction Quick Menu (right-click) ── */+const QUICK_REACTIONS = ['❤️', '😂', '👍', '😮', '😢', '🔥', '👏', '🎉']++function ReactionMenu({ x, y, onReact, onClose }) {+ const ref = useRef(null)- const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']- return `${monthNames[d.getMonth()]} ${d.getDate()}`+ useEffect(() => {+ const close = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose() }+ document.addEventListener('mousedown', close)+ return () => document.removeEventListener('mousedown', close)+ }, [onClose])++ // Clamp to viewport+ const menuWidth = 156+ const clampedLeft = Math.max(menuWidth / 2 + 8, Math.min(x, window.innerWidth - menuWidth / 2 - 8))++ return (+ <div ref={ref} style={{+ position: 'fixed', top: y - 80, left: clampedLeft, transform: 'translateX(-50%)', zIndex: 10000,+ background: 'var(--bg-card)', border: '1px solid var(--border-faint)', borderRadius: 16,+ boxShadow: '0 8px 24px rgba(0,0,0,0.18)', padding: '6px 8px',+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 2, width: menuWidth,+ }}>+ {QUICK_REACTIONS.map(emoji => (+ <button key={emoji} onClick={() => onReact(emoji)} style={{+ width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center',+ background: 'none', border: 'none', cursor: 'pointer', borderRadius: '50%',+ padding: 3, transition: 'transform 0.1s, background 0.1s',+ }}+ onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.2)'; e.currentTarget.style.background = 'var(--bg-hover)' }}+ onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.background = 'none' }}+ >+ <TwemojiImg emoji={emoji} size={18} />+ </button>+ ))}+ </div>+ )+}++/* ── Message Text with clickable URLs ── */+function MessageText({ text }) {+ const parts = text.split(URL_REGEX)+ const urls = text.match(URL_REGEX) || []+ const result = []+ parts.forEach((part, i) => {+ if (part) result.push(part)+ if (urls[i]) result.push(+ <a key={i} href={urls[i]} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'underline', textUnderlineOffset: 2, opacity: 0.85 }}>+ {urls[i]}+ </a>+ )+ })+ return <>{result}</>+}++/* ── Link Preview ── */+const URL_REGEX = /https?:\/\/[^\s<>"']+/g+const previewCache = {}++function LinkPreview({ url, tripId, own, onLoad }) {+ const [data, setData] = useState(previewCache[url] || null)+ const [loading, setLoading] = useState(!previewCache[url])++ useEffect(() => {+ if (previewCache[url]) return+ collabApi.linkPreview(tripId, url).then(d => {+ previewCache[url] = d+ setData(d)+ setLoading(false)+ if (d?.title || d?.description || d?.image) onLoad?.()+ }).catch(() => setLoading(false))+ }, [url, tripId])++ if (loading || !data || (!data.title && !data.description && !data.image)) return null++ const domain = (() => { try { return new URL(url).hostname.replace('www.', '') } catch { return '' } })()++ return (+ <a href={url} target="_blank" rel="noopener noreferrer" style={{+ display: 'block', textDecoration: 'none', marginTop: 6, borderRadius: 12, overflow: 'hidden',+ border: own ? '1px solid rgba(255,255,255,0.15)' : '1px solid var(--border-faint)',+ background: own ? 'rgba(255,255,255,0.1)' : 'var(--bg-secondary)',+ maxWidth: 280, transition: 'opacity 0.15s',+ }}+ onMouseEnter={e => e.currentTarget.style.opacity = '0.85'}+ onMouseLeave={e => e.currentTarget.style.opacity = '1'}+ >+ {data.image && (+ <img src={data.image} alt="" style={{ width: '100%', height: 140, objectFit: 'cover', display: 'block' }}+ onError={e => e.target.style.display = 'none'} />+ )}+ <div style={{ padding: '8px 10px' }}>+ {domain && (+ <div style={{ fontSize: 10, fontWeight: 600, color: own ? 'rgba(255,255,255,0.5)' : 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.3, marginBottom: 2 }}>+ {data.site_name || domain}+ </div>+ )}+ {data.title && (+ <div style={{ fontSize: 12, fontWeight: 600, color: own ? '#fff' : 'var(--text-primary)', lineHeight: 1.3, marginBottom: 2, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>+ {data.title}+ </div>+ )}+ {data.description && (+ <div style={{ fontSize: 11, color: own ? 'rgba(255,255,255,0.7)' : 'var(--text-muted)', lineHeight: 1.3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>+ {data.description}+ </div>+ )}+ </div>+ </a>+ )+}++/* ── Reaction Badge with NOMAD tooltip ── */+function ReactionBadge({ reaction, currentUserId, onReact }) {+ const [hover, setHover] = useState(false)+ const [pos, setPos] = useState({ top: 0, left: 0 })+ const ref = useRef(null)+ const names = reaction.users.map(u => u.username).join(', ')++ return (+ <>+ <button ref={ref} onClick={onReact}+ onMouseEnter={() => {+ if (ref.current) {+ const rect = ref.current.getBoundingClientRect()+ setPos({ top: rect.top - 6, left: rect.left + rect.width / 2 })+ }+ setHover(true)+ }}+ onMouseLeave={() => setHover(false)}+ style={{+ display: 'inline-flex', alignItems: 'center', gap: 2, padding: '1px 3px',+ borderRadius: 99, border: 'none', cursor: 'pointer', fontFamily: 'inherit',+ background: 'transparent', transition: 'transform 0.1s',+ }}+ >+ <TwemojiImg emoji={reaction.emoji} size={16} />+ {reaction.count > 1 && <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-muted)', minWidth: 8 }}>{reaction.count}</span>}+ </button>+ {hover && names && ReactDOM.createPortal(+ <div style={{+ position: 'fixed', top: pos.top, left: pos.left, transform: 'translate(-50%, -100%)',+ pointerEvents: 'none', zIndex: 10000, whiteSpace: 'nowrap',+ background: 'var(--bg-card, white)', color: 'var(--text-primary, #111827)',+ fontSize: 11, fontWeight: 500, padding: '5px 10px', borderRadius: 8,+ boxShadow: '0 4px 12px rgba(0,0,0,0.15)', border: '1px solid var(--border-faint, #e5e7eb)',+ }}>+ {names}+ </div>,+ document.body+ )}+ </>+ )}-/* ─────────────────────────────────────── */-/* Component */-/* ─────────────────────────────────────── */+/* ── Main Component ── */export default function CollabChat({ tripId, currentUser }) {const { t } = useTranslation()+ const is12h = useSettingsStore(s => s.settings.time_format) === '12h'- const [messages, setMessages] = useState([])- const [loading, setLoading] = useState(true)- const [hasMore, setHasMore] = useState(false)+ const [messages, setMessages] = useState([])+ const [loading, setLoading] = useState(true)+ const [hasMore, setHasMore] = useState(false)const [loadingMore, setLoadingMore] = useState(false)- const [text, setText] = useState('')- const [replyTo, setReplyTo] = useState(null)- const [hoveredId, setHoveredId] = useState(null)- const [sending, setSending] = useState(false)-- const scrollRef = useRef(null)+ const [text, setText] = useState('')+ const [replyTo, setReplyTo] = useState(null)+ const [hoveredId, setHoveredId] = useState(null)+ const [sending, setSending] = useState(false)+ const [showEmoji, setShowEmoji] = useState(false)+ const [reactMenu, setReactMenu] = useState(null) // { msgId, x, y }+ const [deletingIds, setDeletingIds] = useState(new Set())++ const containerRef = useRef(null)+ const messagesRef = useRef(messages)+ messagesRef.current = messages+ const scrollRef = useRef(null)const textareaRef = useRef(null)- const isAtBottom = useRef(true)+ const emojiBtnRef = useRef(null)+ const isAtBottom = useRef(true)- /* ── scroll helpers ── */const scrollToBottom = useCallback((behavior = 'auto') => {const el = scrollRef.currentif (!el) return- requestAnimationFrame(() => {- el.scrollTo({ top: el.scrollHeight, behavior })- })+ requestAnimationFrame(() => el.scrollTo({ top: el.scrollHeight, behavior }))}, [])const checkAtBottom = useCallback(() => {@@ -75,66 +335,50 @@ export default function CollabChat({ tripId, currentUser }) {useEffect(() => {let cancelled = falsesetLoading(true)-collabApi.getMessages(tripId).then(data => {if (cancelled) return- const msgs = Array.isArray(data) ? data : data.messages || []+ const msgs = (Array.isArray(data) ? data : data.messages || []).map(m => m.deleted ? { ...m, _deleted: true } : m)setMessages(msgs)setHasMore(msgs.length >= 100)setLoading(false)setTimeout(() => scrollToBottom(), 30)- }).catch(() => {- if (!cancelled) setLoading(false)- })-+ }).catch(() => { if (!cancelled) setLoading(false) })return () => { cancelled = true }}, [tripId, scrollToBottom])- /* ── load more (older messages) ── */+ /* ── load more ── */const handleLoadMore = useCallback(async () => {if (loadingMore || messages.length === 0) returnsetLoadingMore(true)const el = scrollRef.currentconst prevHeight = el ? el.scrollHeight : 0-try {- const oldestId = messages[0]?.id- const data = await collabApi.getMessages(tripId, oldestId)- const older = Array.isArray(data) ? data : data.messages || []-- if (older.length === 0) {- setHasMore(false)- } else {+ const data = await collabApi.getMessages(tripId, messages[0]?.id)+ const older = (Array.isArray(data) ? data : data.messages || []).map(m => m.deleted ? { ...m, _deleted: true } : m)+ if (older.length === 0) { setHasMore(false) }+ else {setMessages(prev => [...older, ...prev])setHasMore(older.length >= 100)- requestAnimationFrame(() => {- if (el) el.scrollTop = el.scrollHeight - prevHeight- })+ requestAnimationFrame(() => { if (el) el.scrollTop = el.scrollHeight - prevHeight })}- } catch {- // silently ignore- } finally {- setLoadingMore(false)- }+ } catch {} finally { setLoadingMore(false) }}, [tripId, loadingMore, messages])/* ── websocket ── */useEffect(() => {const handler = (event) => {if (event.type === 'collab:message:created' && String(event.tripId) === String(tripId)) {- setMessages(prev => {- if (prev.some(m => m.id === event.message.id)) return prev- return [...prev, event.message]- })- if (isAtBottom.current) {- setTimeout(() => scrollToBottom('smooth'), 30)- }+ setMessages(prev => prev.some(m => m.id === event.message.id) ? prev : [...prev, event.message])+ if (isAtBottom.current) setTimeout(() => scrollToBottom('smooth'), 30)}if (event.type === 'collab:message:deleted' && String(event.tripId) === String(tripId)) {- setMessages(prev => prev.filter(m => m.id !== event.messageId))+ setMessages(prev => prev.map(m => m.id === event.messageId ? { ...m, _deleted: true } : m))+ if (isAtBottom.current) setTimeout(() => scrollToBottom('smooth'), 50)+ }+ if (event.type === 'collab:message:reacted' && String(event.tripId) === String(tripId)) {+ setMessages(prev => prev.map(m => m.id === event.messageId ? { ...m, reactions: event.reactions } : m))}}-addListener(handler)return () => removeListener(handler)}, [tripId, scrollToBottom])@@ -145,7 +389,9 @@ export default function CollabChat({ tripId, currentUser }) {const ta = textareaRef.currentif (ta) {ta.style.height = 'auto'- ta.style.height = Math.min(ta.scrollHeight, 3 * 20 + 18) + 'px'+ const h = Math.min(ta.scrollHeight, 100)+ ta.style.height = h + 'px'+ ta.style.overflowY = ta.scrollHeight > 100 ? 'auto' : 'hidden'}}, [])@@ -153,164 +399,92 @@ export default function CollabChat({ tripId, currentUser }) {const handleSend = useCallback(async () => {const body = text.trim()if (!body || sending) return-setSending(true)try {const payload = { text: body }if (replyTo) payload.reply_to = replyTo.idconst data = await collabApi.sendMessage(tripId, payload)if (data?.message) {- setMessages(prev => {- if (prev.some(m => m.id === data.message.id)) return prev- return [...prev, data.message]- })+ setMessages(prev => prev.some(m => m.id === data.message.id) ? prev : [...prev, data.message])}- setText('')- setReplyTo(null)- if (textareaRef.current) {- textareaRef.current.style.height = 'auto'- }- scrollToBottom('smooth')- } catch {- // keep text on failure so user can retry- } finally {- setSending(false)- }+ setText(''); setReplyTo(null); setShowEmoji(false)+ if (textareaRef.current) textareaRef.current.style.height = 'auto'+ isAtBottom.current = true+ setTimeout(() => scrollToBottom('smooth'), 50)+ } catch {} finally { setSending(false) }}, [text, sending, replyTo, tripId, scrollToBottom])- /* ── keyboard ── */const handleKeyDown = useCallback((e) => {- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault()- handleSend()- }+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend() }}, [handleSend])- /* ── delete ── */const handleDelete = useCallback(async (msgId) => {+ const msg = messages.find(m => m.id === msgId)+ requestAnimationFrame(() => {+ setDeletingIds(prev => new Set(prev).add(msgId))+ })+ setTimeout(async () => {+ try {+ await collabApi.deleteMessage(tripId, msgId)+ setMessages(prev => prev.map(m => m.id === msgId ? { ...m, _deleted: true } : m))+ } catch {}+ setDeletingIds(prev => { const s = new Set(prev); s.delete(msgId); return s })+ }, 400)+ }, [tripId])++ const handleReact = useCallback(async (msgId, emoji) => {+ setReactMenu(null)try {- await collabApi.deleteMessage(tripId, msgId)- } catch {- // ignore- }+ const data = await collabApi.reactMessage(tripId, msgId, emoji)+ setMessages(prev => prev.map(m => m.id === msgId ? { ...m, reactions: data.reactions } : m))+ } catch {}}, [tripId])- /* ── find a replied-to message ── */- const findMessage = useCallback((id) => messages.find(m => m.id === id), [messages])+ const handleEmojiSelect = useCallback((emoji) => {+ setText(prev => prev + emoji)+ textareaRef.current?.focus()+ }, [])- /* ── helpers ── */const isOwn = (msg) => String(msg.user_id) === String(currentUser.id)- const font = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif"+ // Check if message is only emoji (1-3 emojis, no other text)+ const isEmojiOnly = (text) => {+ const emojiRegex = /^(?:\p{Emoji_Presentation}|\p{Extended_Pictographic}[\uFE0F]?(?:\u200D\p{Extended_Pictographic}[\uFE0F]?)*){1,3}$/u+ return emojiRegex.test(text.trim())+ }- /* ───────── render: loading ───────── */+ /* ── Loading ── */if (loading) {return (- <div style={{- display: 'flex',- flexDirection: 'column',- flex: 1,- fontFamily: font,- position: 'relative',- overflow: 'hidden',- }}>- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- gap: 10,- color: 'var(--text-faint)',- userSelect: 'none',- padding: 32,- }}>- <div style={{- width: 24,- height: 24,- border: '2px solid var(--border-faint)',- borderTopColor: 'var(--accent)',- borderRadius: '50%',- animation: 'spin .7s linear infinite',- }} />- <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>- </div>+ <div style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'center' }}>+ <div style={{ width: 24, height: 24, border: '2px solid var(--border-faint)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'spin .7s linear infinite' }} />+ <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style></div>)}- /* ───────── render: main ───────── */+ /* ── Main ── */return (- <div style={{- display: 'flex',- flexDirection: 'column',- flex: 1,- fontFamily: font,- position: 'relative',- overflow: 'hidden',- }}>- {/* ── messages area ── */}+ <div ref={containerRef} style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden', position: 'relative', minHeight: 0, height: '100%' }}>+ {/* Messages */}{messages.length === 0 ? (- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- gap: 10,- color: 'var(--text-faint)',- userSelect: 'none',- padding: 32,- }}>- <MessageCircle size={36} strokeWidth={1.3} style={{ opacity: 0.5 }} />- <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-faint)' }}>- {t('collab.chat.empty')}- </span>- <span style={{ fontSize: 12, color: 'var(--text-faint)', opacity: 0.7 }}>- {t('collab.chat.emptyDesc') || ''}- </span>+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--text-faint)', padding: 32 }}>+ <MessageCircle size={40} strokeWidth={1.2} style={{ opacity: 0.4 }} />+ <span style={{ fontSize: 14, fontWeight: 600 }}>{t('collab.chat.empty')}</span>+ <span style={{ fontSize: 12, opacity: 0.6 }}>{t('collab.chat.emptyDesc') || ''}</span></div>) : (- <div- ref={scrollRef}- style={{- flex: 1,- overflowY: 'auto',- overflowX: 'hidden',- padding: '12px 16px 8px',- display: 'flex',- flexDirection: 'column',- gap: 4,- }}- onScroll={checkAtBottom}- >- {/* load more */}+ <div ref={scrollRef} onScroll={checkAtBottom} className="chat-scroll" style={{+ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px 14px 4px', WebkitOverflowScrolling: 'touch',+ display: 'flex', flexDirection: 'column', gap: 1,+ }}>{hasMore && (- <div style={{- display: 'flex',- justifyContent: 'center',- padding: '4px 0 8px',- }}>- <button- style={{- display: 'inline-flex',- alignItems: 'center',- gap: 4,- fontSize: 11,- fontWeight: 600,- color: 'var(--text-muted)',- background: 'var(--bg-secondary)',- border: '1px solid var(--border-faint)',- borderRadius: 99,- padding: '5px 14px',- cursor: 'pointer',- fontFamily: font,- textTransform: 'uppercase',- letterSpacing: 0.3,- }}- onClick={handleLoadMore}- disabled={loadingMore}- >+ <div style={{ display: 'flex', justifyContent: 'center', padding: '4px 0 10px' }}>+ <button onClick={handleLoadMore} disabled={loadingMore} style={{+ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600,+ color: 'var(--text-muted)', background: 'var(--bg-secondary)', border: '1px solid var(--border-faint)',+ borderRadius: 99, padding: '5px 14px', cursor: 'pointer', fontFamily: 'inherit',+ }}><ChevronUp size={13} />{loadingMore ? '...' : t('collab.chat.loadMore')}</button>@@ -319,297 +493,283 @@ export default function CollabChat({ tripId, currentUser }) {{messages.map((msg, idx) => {const own = isOwn(msg)- const repliedMsg = msg.reply_to_id ? findMessage(msg.reply_to_id) : nullconst prevMsg = messages[idx - 1]+ const nextMsg = messages[idx + 1]const isNewGroup = idx === 0 || String(prevMsg?.user_id) !== String(msg.user_id)- const showHeader = !own && isNewGroup+ const isLastInGroup = !nextMsg || String(nextMsg?.user_id) !== String(msg.user_id)+ const showDate = shouldShowDateSeparator(msg, prevMsg)+ const showAvatar = !own && isLastInGroup+ const bigEmoji = isEmojiOnly(msg.text)+ const hasReply = msg.reply_text || msg.reply_to+ // Deleted message placeholder+ if (msg._deleted) {+ return (+ <React.Fragment key={msg.id}>+ {showDate && (+ <div style={{ display: 'flex', justifyContent: 'center', padding: '14px 0 6px' }}>+ <span style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-faint)', background: 'var(--bg-secondary)', padding: '3px 12px', borderRadius: 99, letterSpacing: 0.3, textTransform: 'uppercase' }}>+ {formatDateSeparator(msg.created_at, t)}+ </span>+ </div>+ )}+ <div style={{ display: 'flex', justifyContent: 'center', padding: '4px 0' }}>+ <span style={{ fontSize: 11, color: 'var(--text-faint)', fontStyle: 'italic' }}>+ {msg.username} {t('collab.chat.deletedMessage') || 'deleted a message'} · {formatTime(msg.created_at, is12h)}+ </span>+ </div>+ </React.Fragment>+ )+ }++ // Bubble border radius — iMessage style tails+ const br = own+ ? `18px 18px ${isLastInGroup ? '4px' : '18px'} 18px`+ : `18px 18px 18px ${isLastInGroup ? '4px' : '18px'}`return (- <div- key={msg.id}- style={{- display: 'flex',- flexDirection: 'column',- alignItems: own ? 'flex-end' : 'flex-start',- marginTop: isNewGroup ? 12 : 0,- }}- >- {/* username + avatar for others */}- {showHeader && (- <div style={{- display: 'flex',- alignItems: 'center',- gap: 6,- marginBottom: 4,- paddingLeft: 2,- }}>- {msg.user_avatar ? (- <img- src={msg.user_avatar}- alt=""- style={{- width: 20,- height: 20,- borderRadius: '50%',- objectFit: 'cover',- flexShrink: 0,- }}- />- ) : (- <span style={{- width: 20,- height: 20,- borderRadius: '50%',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- fontSize: 9,- fontWeight: 700,- color: 'var(--text-primary)',- background: 'var(--bg-tertiary)',- flexShrink: 0,- lineHeight: 1,- }}>- {(msg.username || '?')[0].toUpperCase()}- </span>- )}+ <React.Fragment key={msg.id}>+ {/* Date separator */}+ {showDate && (+ <div style={{ display: 'flex', justifyContent: 'center', padding: '14px 0 6px' }}><span style={{- fontSize: 10,- fontWeight: 600,- color: 'var(--text-faint)',- lineHeight: 1,+ fontSize: 10, fontWeight: 600, color: 'var(--text-faint)',+ background: 'var(--bg-secondary)', padding: '3px 12px', borderRadius: 99,+ letterSpacing: 0.3, textTransform: 'uppercase',}}>- {msg.username}+ {formatDateSeparator(msg.created_at, t)}</span></div>)}- {/* reply quote */}- {repliedMsg && (- <div style={{- padding: '6px 10px',- borderLeft: '2px solid var(--accent)',- background: 'var(--bg-secondary)',- borderRadius: 6,- fontSize: 11,- lineHeight: 1.35,- marginBottom: 4,- maxWidth: '75%',- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- color: 'var(--text-muted)',- alignSelf: own ? 'flex-end' : 'flex-start',- }}>- <strong style={{ fontWeight: 600 }}>{repliedMsg.username}: </strong>- {(repliedMsg.text || '').slice(0, 80)}- {(repliedMsg.text || '').length > 80 ? '...' : ''}- </div>- )}-- {/* bubble with hover actions */}- <div- style={{ position: 'relative', maxWidth: '75%' }}- onMouseEnter={() => setHoveredId(msg.id)}- onMouseLeave={() => setHoveredId(null)}- >- <div style={{- background: own ? 'var(--accent)' : 'var(--bg-secondary)',- color: own ? 'var(--accent-text)' : 'var(--text-primary)',- borderRadius: own ? '14px 14px 4px 14px' : '14px 14px 14px 4px',- padding: '8px 12px',- fontSize: 13,- lineHeight: 1.45,- wordBreak: 'break-word',- whiteSpace: 'pre-wrap',- }}>- {msg.text}- </div>+ <div style={{+ display: 'flex', alignItems: own ? 'flex-end' : 'flex-start',+ flexDirection: own ? 'row-reverse' : 'row',+ gap: 6, marginTop: isNewGroup ? 10 : 1,+ paddingLeft: own ? 40 : 0, paddingRight: own ? 0 : 40,+ transition: 'transform 0.3s ease, opacity 0.3s ease, max-height 0.3s ease',+ ...(deletingIds.has(msg.id) ? { transform: 'scale(0.3)', opacity: 0, maxHeight: 0, marginTop: 0, overflow: 'hidden' } : {}),+ }}>+ {/* Avatar slot for others */}+ {!own && (+ <div style={{ width: 28, flexShrink: 0, alignSelf: 'flex-end' }}>+ {showAvatar && (+ msg.user_avatar ? (+ <img src={msg.user_avatar} alt="" style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }} />+ ) : (+ <div style={{+ width: 28, height: 28, borderRadius: '50%', background: 'var(--bg-tertiary)',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)',+ }}>+ {(msg.username || '?')[0].toUpperCase()}+ </div>+ )+ )}+ </div>+ )}++ <div style={{ display: 'flex', flexDirection: 'column', alignItems: own ? 'flex-end' : 'flex-start', maxWidth: '78%', minWidth: 0 }}>+ {/* Username for others at group start */}+ {!own && isNewGroup && (+ <span style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-faint)', marginBottom: 2, paddingLeft: 4 }}>+ {msg.username}+ </span>+ )}- {/* action buttons */}- <div style={{- position: 'absolute',- top: -10,- display: 'flex',- gap: 2,- opacity: hoveredId === msg.id ? 1 : 0,- pointerEvents: hoveredId === msg.id ? 'auto' : 'none',- transition: 'opacity .12s ease',- ...(own ? { right: 4 } : { left: 4 }),- }}>- <button- style={{- width: 22,- height: 22,- borderRadius: '50%',- border: '1px solid var(--border-faint)',- background: 'var(--bg-card)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: 'pointer',- color: 'var(--text-muted)',- padding: 0,- flexShrink: 0,+ {/* Bubble */}+ <div+ style={{ position: 'relative' }}+ onMouseEnter={() => setHoveredId(msg.id)}+ onMouseLeave={() => setHoveredId(null)}+ onContextMenu={e => { e.preventDefault(); setReactMenu({ msgId: msg.id, x: e.clientX, y: e.clientY }) }}+ onTouchEnd={e => {+ const now = Date.now()+ const lastTap = e.currentTarget.dataset.lastTap || 0+ if (now - lastTap < 300) {+ e.preventDefault()+ const touch = e.changedTouches?.[0]+ if (touch) setReactMenu({ msgId: msg.id, x: touch.clientX, y: touch.clientY })+ }+ e.currentTarget.dataset.lastTap = now}}- title="Reply"- onClick={() => setReplyTo(msg)}>- <Reply size={11} />- </button>- {own && (- <button- style={{- width: 22,- height: 22,- borderRadius: '50%',- border: '1px solid var(--border-faint)',- background: 'var(--bg-card)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: 'pointer',- color: 'var(--text-muted)',- padding: 0,- flexShrink: 0,+ {bigEmoji ? (+ <div style={{ fontSize: 40, lineHeight: 1.2, padding: '2px 0' }}>+ {msg.text}+ </div>+ ) : (+ <div style={{+ background: own ? '#007AFF' : 'var(--bg-secondary)',+ color: own ? '#fff' : 'var(--text-primary)',+ borderRadius: br, padding: hasReply ? '4px 4px 8px 4px' : '8px 14px',+ fontSize: 14, lineHeight: 1.4, wordBreak: 'break-word', whiteSpace: 'pre-wrap',+ }}>+ {/* Inline reply quote */}+ {hasReply && (+ <div style={{+ padding: '5px 10px', marginBottom: 4, borderRadius: 12,+ background: own ? 'rgba(255,255,255,0.15)' : 'var(--bg-tertiary)',+ fontSize: 12, lineHeight: 1.3,+ }}>+ <div style={{ fontWeight: 600, fontSize: 11, opacity: 0.7, marginBottom: 1 }}>+ {msg.reply_username || ''}+ </div>+ <div style={{ opacity: 0.8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {(msg.reply_text || '').slice(0, 80)}+ </div>+ </div>+ )}+ {hasReply ? (+ <div style={{ padding: '0 10px 4px' }}><MessageText text={msg.text} /></div>+ ) : <MessageText text={msg.text} />}+ {(msg.text.match(URL_REGEX) || []).slice(0, 1).map(url => (+ <LinkPreview key={url} url={url} tripId={tripId} own={own} onLoad={() => { if (isAtBottom.current) setTimeout(() => scrollToBottom('smooth'), 50) }} />+ ))}+ </div>+ )}++ {/* Hover actions */}+ <div style={{+ position: 'absolute', top: -14,+ display: 'flex', gap: 2,+ opacity: hoveredId === msg.id ? 1 : 0,+ pointerEvents: hoveredId === msg.id ? 'auto' : 'none',+ transition: 'opacity .1s',+ ...(own ? { left: -6 } : { right: -6 }),+ }}>+ <button onClick={() => setReplyTo(msg)} title="Reply" style={{+ width: 24, height: 24, borderRadius: '50%', border: 'none',+ background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center',+ cursor: 'pointer', color: 'var(--accent-text)', padding: 0,+ boxShadow: '0 2px 8px rgba(0,0,0,0.15)', transition: 'transform 0.12s',}}- title="Delete"- onClick={() => handleDelete(msg.id)}- >- <Trash2 size={11} />- </button>+ onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.2)' }}+ onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)' }}+ >+ <Reply size={11} />+ </button>+ {own && (+ <button onClick={() => handleDelete(msg.id)} title="Delete" style={{+ width: 24, height: 24, borderRadius: '50%', border: 'none',+ background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center',+ cursor: 'pointer', color: 'var(--accent-text)', padding: 0,+ boxShadow: '0 2px 8px rgba(0,0,0,0.15)', transition: 'transform 0.12s, background 0.15s, color 0.15s',+ }}+ onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.2)'; e.currentTarget.style.background = '#ef4444'; e.currentTarget.style.color = '#fff' }}+ onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.background = 'var(--accent)'; e.currentTarget.style.color = 'var(--accent-text)' }}+ >+ <Trash2 size={11} />+ </button>+ )}+ </div>+ </div>++ {/* Reactions — iMessage style floating badge */}+ {msg.reactions?.length > 0 && (+ <div style={{+ display: 'flex', gap: 3, marginTop: -6, marginBottom: 4,+ justifyContent: own ? 'flex-end' : 'flex-start',+ paddingLeft: own ? 0 : 8, paddingRight: own ? 8 : 0,+ position: 'relative', zIndex: 1,+ }}>+ <div style={{+ display: 'inline-flex', alignItems: 'center', gap: 2, padding: '3px 6px',+ borderRadius: 99, background: 'var(--bg-card)',+ boxShadow: '0 1px 6px rgba(0,0,0,0.12)', border: '1px solid var(--border-faint)',+ }}>+ {msg.reactions.map(r => {+ const myReaction = r.users.some(u => String(u.user_id) === String(currentUser.id))+ return (+ <ReactionBadge key={r.emoji} reaction={r} currentUserId={currentUser.id} onReact={() => handleReact(msg.id, r.emoji)} />+ )+ })}+ </div>+ </div>+ )}++ {/* Timestamp — only on last message of group */}+ {isLastInGroup && (+ <span style={{ fontSize: 9, color: 'var(--text-faint)', marginTop: 2, padding: '0 4px' }}>+ {formatTime(msg.created_at, is12h)}+ </span>)}</div></div>-- {/* timestamp */}- <span style={{- fontSize: 9,- color: 'var(--text-faint)',- marginTop: 2,- paddingLeft: 2,- paddingRight: 2,- lineHeight: 1,- }}>- {formatRelativeTime(msg.created_at, t)}- </span>- </div>+ </React.Fragment>)})}</div>)}- {/* ── composer ── */}- <div style={{- flexShrink: 0,- padding: 12,- borderTop: '1px solid var(--border-faint)',- background: 'var(--bg-card)',- }}>- {/* reply preview */}+ {/* Composer */}+ <div style={{ flexShrink: 0, padding: '8px 12px calc(12px + env(safe-area-inset-bottom, 0px))', borderTop: '1px solid var(--border-faint)', background: 'var(--bg-card)' }}>+ {/* Reply preview */}{replyTo && (<div style={{- display: 'flex',- alignItems: 'center',- gap: 8,- marginBottom: 8,- padding: '6px 10px',- borderRadius: 6,- background: 'var(--bg-secondary)',- borderLeft: '2px solid var(--accent)',- fontSize: 12,- color: 'var(--text-muted)',- lineHeight: 1.3,+ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8,+ padding: '6px 10px', borderRadius: 10, background: 'var(--bg-secondary)',+ borderLeft: '3px solid #007AFF', fontSize: 12, color: 'var(--text-muted)',}}>- <Reply size={13} style={{ flexShrink: 0, opacity: 0.6 }} />- <span style={{- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}>+ <Reply size={12} style={{ flexShrink: 0, opacity: 0.5 }} />+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}><strong>{replyTo.username}</strong>: {(replyTo.text || '').slice(0, 60)}- {(replyTo.text || '').length > 60 ? '...' : ''}- </span>- <span- style={{- marginLeft: 'auto',- cursor: 'pointer',- color: 'var(--text-faint)',- fontSize: 16,- fontWeight: 400,- lineHeight: 1,- padding: '0 2px',- flexShrink: 0,- }}- onClick={() => setReplyTo(null)}- >- ×</span>+ <button onClick={() => setReplyTo(null)} style={{+ background: 'none', border: 'none', cursor: 'pointer', padding: 2, color: 'var(--text-faint)',+ display: 'flex', flexShrink: 0,+ }}>+ <X size={14} />+ </button></div>)}- <div style={{- display: 'flex',- alignItems: 'flex-end',- gap: 8,- }}>+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6 }}>+ {/* Emoji button */}+ <button ref={emojiBtnRef} onClick={() => setShowEmoji(!showEmoji)} style={{+ width: 34, height: 34, borderRadius: '50%', border: 'none',+ background: showEmoji ? 'var(--bg-hover)' : 'transparent',+ color: 'var(--text-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center',+ cursor: 'pointer', padding: 0, flexShrink: 0, transition: 'background 0.15s',+ }}>+ <Smile size={20} />+ </button>+<textarearef={textareaRef}rows={1}style={{- flex: 1,- resize: 'none',- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- lineHeight: 1.4,- fontFamily: font,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- outline: 'none',- maxHeight: 3 * 20 + 18,- overflow: 'auto',- transition: 'border-color .15s ease',+ flex: 1, resize: 'none', border: '1px solid var(--border-primary)', borderRadius: 20,+ padding: '8px 14px', fontSize: 14, lineHeight: 1.4, fontFamily: 'inherit',+ background: 'var(--bg-input)', color: 'var(--text-primary)', outline: 'none',+ maxHeight: 100, overflowY: 'hidden',}}placeholder={t('collab.chat.placeholder')}value={text}onChange={handleTextChange}onKeyDown={handleKeyDown}- onFocus={() => {- if (textareaRef.current) {- textareaRef.current.style.borderColor = 'var(--accent)'- }- }}- onBlur={() => {- if (textareaRef.current) {- textareaRef.current.style.borderColor = 'var(--border-primary)'- }- }}/>- <button- style={{- width: 32,- height: 32,- borderRadius: '50%',- border: 'none',- background: 'var(--accent)',- color: 'var(--accent-text)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: (!text.trim() || sending) ? 'default' : 'pointer',- flexShrink: 0,- opacity: (!text.trim() || sending) ? 0.4 : 1,- transition: 'opacity .15s ease',- }}- onClick={handleSend}- disabled={!text.trim() || sending}- >- <Send size={14} style={{ marginLeft: 1 }} />++ {/* Send */}+ <button onClick={handleSend} disabled={!text.trim() || sending} style={{+ width: 34, height: 34, borderRadius: '50%', border: 'none',+ background: text.trim() ? '#007AFF' : 'var(--border-primary)',+ color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',+ cursor: text.trim() ? 'pointer' : 'default', flexShrink: 0,+ transition: 'background 0.15s',+ }}>+ <ArrowUp size={18} strokeWidth={2.5} /></button></div></div>++ {/* Emoji picker */}+ {showEmoji && <EmojiPicker onSelect={handleEmojiSelect} onClose={() => setShowEmoji(false)} anchorRef={emojiBtnRef} containerRef={containerRef} />}++ {/* Reaction quick menu (right-click) */}+ {reactMenu && ReactDOM.createPortal(+ <ReactionMenu x={reactMenu.x} y={reactMenu.y} onReact={(emoji) => handleReact(reactMenu.msgId, emoji)} onClose={() => setReactMenu(null)} />,+ document.body+ )}</div>)}diff --git a/client/src/components/Collab/CollabNotes.jsx b/client/src/components/Collab/CollabNotes.jsxindex 2169aa2f1..8423a8c89 100644--- a/client/src/components/Collab/CollabNotes.jsx+++ b/client/src/components/Collab/CollabNotes.jsx@@ -1,12 +1,100 @@-import React, { useState, useEffect, useCallback } from 'react'+import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'import ReactDOM from 'react-dom'-import { Plus, Trash2, Pin, PinOff, Pencil, X, Check } from 'lucide-react'+import { Plus, Trash2, Pin, PinOff, Pencil, X, Check, StickyNote, Settings, ExternalLink } from 'lucide-react'import { collabApi } from '../../api/client'import { addListener, removeListener } from '../../api/websocket'import { useTranslation } from '../../i18n'const FONT = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif"+// ── Website Thumbnail (fetches OG image) ────────────────────────────────────+const ogCache = {}++function WebsiteThumbnail({ url, tripId, color }) {+ const [data, setData] = useState(ogCache[url] || null)+ const [failed, setFailed] = useState(false)++ useEffect(() => {+ if (ogCache[url]) { setData(ogCache[url]); return }+ collabApi.linkPreview(tripId, url).then(d => { ogCache[url] = d; setData(d) }).catch(() => setFailed(true))+ }, [url, tripId])++ const domain = (() => { try { return new URL(url).hostname.replace('www.', '') } catch { return 'link' } })()++ return (+ <a href={url} target="_blank" rel="noopener noreferrer" title={data?.title || url}+ style={{+ width: 48, height: 48, borderRadius: 8, cursor: 'pointer', overflow: 'hidden',+ background: data?.image ? 'none' : 'var(--bg-tertiary)', border: 'none',+ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,+ textDecoration: 'none', transition: 'transform 0.12s, box-shadow 0.12s', flexShrink: 0,+ }}+ onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.08)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}+ onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }}>+ {data?.image && !failed ? (+ <img src={data.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={() => setFailed(true)} />+ ) : (+ <>+ <ExternalLink size={14} color="var(--text-muted)" />+ <span style={{ fontSize: 7, fontWeight: 600, color: 'var(--text-muted)', maxWidth: 42, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textAlign: 'center' }}>+ {domain}+ </span>+ </>+ )}+ </a>+ )+}++// ── File Preview Portal ─────────────────────────────────────────────────────+function FilePreviewPortal({ file, onClose }) {+ if (!file) return null+ const url = file.url || `/uploads/${file.filename}`+ const isImage = file.mime_type?.startsWith('image/')+ const isPdf = file.mime_type === 'application/pdf'+ const isTxt = file.mime_type?.startsWith('text/')++ return ReactDOM.createPortal(+ <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.88)', zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }} onClick={onClose}>+ {isImage ? (+ /* Image lightbox — floating controls */+ <div style={{ position: 'relative', maxWidth: '90vw', maxHeight: '90vh' }} onClick={e => e.stopPropagation()}>+ <img src={url} alt={file.original_name} style={{ maxWidth: '90vw', maxHeight: '90vh', objectFit: 'contain', borderRadius: 8, display: 'block' }} />+ <div style={{ position: 'absolute', top: -36, left: 0, right: 0, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 4px' }}>+ <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '70%' }}>{file.original_name}</span>+ <div style={{ display: 'flex', gap: 8 }}>+ <a href={url} target="_blank" rel="noreferrer" style={{ color: 'rgba(255,255,255,0.7)', display: 'flex' }}><ExternalLink size={15} /></a>+ <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(255,255,255,0.7)', display: 'flex', padding: 0 }}><X size={17} /></button>+ </div>+ </div>+ </div>+ ) : (+ /* Document viewer — card with header */+ <div style={{ width: '100%', maxWidth: 950, height: '94vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-card)', borderRadius: 12, overflow: 'hidden', boxShadow: '0 20px 60px rgba(0,0,0,0.3)' }} onClick={e => e.stopPropagation()}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px', borderBottom: '1px solid var(--border-primary)', flexShrink: 0 }}>+ <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{file.original_name}</span>+ <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>+ <a href={url} target="_blank" rel="noreferrer" style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11, color: 'var(--text-muted)', textDecoration: 'none' }}><ExternalLink size={13} /></a>+ <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', padding: 2 }}><X size={18} /></button>+ </div>+ </div>+ {(isPdf || isTxt) ? (+ <object data={`${url}#view=FitH`} type={file.mime_type} style={{ flex: 1, width: '100%', border: 'none', background: '#fff' }} title={file.original_name}>+ <p style={{ padding: 24, textAlign: 'center', color: 'var(--text-muted)' }}>+ <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--text-primary)', textDecoration: 'underline' }}>Download</a>+ </p>+ </object>+ ) : (+ <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40 }}>+ <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--text-primary)', textDecoration: 'underline', fontSize: 14 }}>Download {file.original_name}</a>+ </div>+ )}+ </div>+ )}+ </div>,+ document.body+ )+}+const NOTE_COLORS = [{ value: '#6366f1', label: 'Indigo' },{ value: '#ef4444', label: 'Red' },@@ -16,19 +104,19 @@ const NOTE_COLORS = [{ value: '#8b5cf6', label: 'Violet' },]-const formatTimestamp = (ts) => {+const formatTimestamp = (ts, t, locale) => {if (!ts) return ''- const d = new Date(ts)+ const d = new Date(ts.endsWith?.('Z') ? ts : ts + 'Z')const now = new Date()const diffMs = now - dconst diffMins = Math.floor(diffMs / 60000)- if (diffMins < 1) return 'just now'- if (diffMins < 60) return `${diffMins}m ago`+ if (diffMins < 1) return t('collab.chat.justNow') || 'just now'+ if (diffMins < 60) return t('collab.chat.minutesAgo', { n: diffMins }) || `${diffMins}m ago`const diffHrs = Math.floor(diffMins / 60)- if (diffHrs < 24) return `${diffHrs}h ago`+ if (diffHrs < 24) return t('collab.chat.hoursAgo', { n: diffHrs }) || `${diffHrs}h ago`const diffDays = Math.floor(diffHrs / 24)- if (diffDays < 7) return `${diffDays}d ago`- return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })+ if (diffDays < 7) return t('collab.notes.daysAgo', { n: diffDays }) || `${diffDays}d ago`+ return d.toLocaleDateString(locale || undefined, { month: 'short', day: 'numeric' })}// ── Avatar ──────────────────────────────────────────────────────────────────@@ -73,16 +161,20 @@ function UserAvatar({ user, size = 14 }) {}// ── New Note Modal (portal to body) ─────────────────────────────────────────-function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {- const [title, setTitle] = useState('')- const [content, setContent] = useState('')- const [category, setCategory] = useState('')- const [customCategory, setCustomCategory] = useState('')- const [color, setColor] = useState(NOTE_COLORS[0].value)+function NoteFormModal({ onClose, onSubmit, onDeleteFile, existingCategories, categoryColors, getCategoryColor, note, tripId, t }) {+ const isEdit = !!note+ const allCategories = [...new Set([...existingCategories, ...Object.keys(categoryColors || {})])].filter(Boolean)++ const [title, setTitle] = useState(note?.title || '')+ const [content, setContent] = useState(note?.content || '')+ const [category, setCategory] = useState(note?.category || allCategories[0] || '')+ const [website, setWebsite] = useState(note?.website || '')+ const [pendingFiles, setPendingFiles] = useState([])+ const [existingAttachments, setExistingAttachments] = useState(note?.attachments || [])const [submitting, setSubmitting] = useState(false)+ const fileRef = useRef(null)- const isCustom = category === '__custom__'- const finalCategory = isCustom ? customCategory.trim() : category+ const finalCategory = categoryconst handleSubmit = async (e) => {e.preventDefault()@@ -93,16 +185,24 @@ function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {title: title.trim(),content: content.trim(),category: finalCategory || null,- color,+ color: getCategoryColor(finalCategory),+ website: website.trim() || null,+ _pendingFiles: pendingFiles,})onClose()} catch {- // error handled upstream} finally {setSubmitting(false)}}+ const handleDeleteAttachment = async (fileId) => {+ if (onDeleteFile && note) {+ await onDeleteFile(note.id, fileId)+ setExistingAttachments(prev => prev.filter(a => a.id !== fileId))+ }+ }+const canSubmit = title.trim() && !submittingreturn ReactDOM.createPortal(@@ -133,6 +233,18 @@ function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {border: '1px solid var(--border-faint)',}}onClick={e => e.stopPropagation()}+ onPaste={e => {+ const items = e.clipboardData?.items+ if (!items) return+ for (const item of items) {+ if (item.type.startsWith('image/') || item.type === 'application/pdf') {+ e.preventDefault()+ const file = item.getAsFile()+ if (file) setPendingFiles(prev => [...prev, file])+ return+ }+ }+ }}onSubmit={handleSubmit}>{/* Modal header */}@@ -150,7 +262,7 @@ function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {margin: 0,fontFamily: FONT,}}>- {t('collab.notes.new')}+ {isEdit ? t('collab.notes.edit') : t('collab.notes.new')}</h3><buttontype="button"@@ -244,102 +356,68 @@ function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {/></div>- {/* Category */}+ {/* Category pills */}<div>- <div style={{- fontSize: 9,- fontWeight: 600,- color: 'var(--text-faint)',- textTransform: 'uppercase',- letterSpacing: '0.05em',- marginBottom: 4,- fontFamily: FONT,- }}>+ <div style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6, fontFamily: FONT }}>{t('collab.notes.category')}</div>- <select- value={category}- onChange={e => setCategory(e.target.value)}- style={{- width: '100%',- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- boxSizing: 'border-box',- cursor: 'pointer',- appearance: 'none',- }}- >- <option value="">{t('collab.notes.noCategory')}</option>- {existingCategories.map(cat => (- <option key={cat} value={cat}>{cat}</option>- ))}- <option value="__custom__">{t('collab.notes.newCategory')}</option>- </select>- {isCustom && (- <input- value={customCategory}- onChange={e => setCustomCategory(e.target.value)}- placeholder={t('collab.notes.categoryPlaceholder')}- autoFocus- style={{- width: '100%',- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- boxSizing: 'border-box',- marginTop: 8,- }}- />- )}+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>+ {allCategories.map(cat => {+ const c = getCategoryColor(cat)+ const active = category === cat+ return (+ <button key={cat} type="button" onClick={() => setCategory(cat)}+ style={{ padding: '4px 12px', borderRadius: 99, border: active ? `1.5px solid ${c}` : '1px solid var(--border-faint)', background: active ? `${c}18` : 'transparent', color: active ? c : 'var(--text-muted)', fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: FONT }}>+ {cat}+ </button>+ )+ })}+ </div></div>- {/* Color picker */}+ {/* Website */}<div>- <div style={{- fontSize: 9,- fontWeight: 600,- color: 'var(--text-faint)',- textTransform: 'uppercase',- letterSpacing: '0.05em',- marginBottom: 4,- fontFamily: FONT,- }}>- {t('collab.notes.color')}+ <div style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4, fontFamily: FONT }}>+ {t('collab.notes.website')}</div>- <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>- {NOTE_COLORS.map(c => (- <button- key={c.value}- type="button"- onClick={() => setColor(c.value)}- title={c.label}- aria-label={c.label}- style={{- width: 26,- height: 26,- borderRadius: 8,- background: c.value,- border: color === c.value- ? '2px solid var(--text-primary)'- : '2px solid transparent',- cursor: 'pointer',- transition: 'transform 0.15s',- transform: color === c.value ? 'scale(1.15)' : 'scale(1)',- padding: 0,- }}- />+ <input value={website} onChange={e => setWebsite(e.target.value)}+ placeholder={t('collab.notes.websitePlaceholder')}+ style={{ width: '100%', border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px', fontSize: 13, background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} />+ </div>++ {/* File attachments */}+ <div>+ <div style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4, fontFamily: FONT }}>+ {t('collab.notes.attachFiles')}+ </div>+ <input id="note-file-input" ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={e => { setPendingFiles(prev => [...prev, ...Array.from(e.target.files)]); e.target.value = '' }} />+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>+ {/* Existing attachments (edit mode) */}+ {existingAttachments.map(a => {+ const isImage = a.mime_type?.startsWith('image/')+ return (+ <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '3px 8px', borderRadius: 8, background: 'var(--bg-secondary)', fontSize: 11, color: 'var(--text-muted)' }}>+ {isImage && <img src={a.url} style={{ width: 18, height: 18, objectFit: 'cover', borderRadius: 3 }} />}+ {(a.original_name || '').length > 20 ? a.original_name.slice(0, 17) + '...' : a.original_name}+ <button type="button" onClick={() => handleDeleteAttachment(a.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#ef4444', padding: 0, display: 'flex' }}>+ <X size={10} />+ </button>+ </div>+ )+ })}+ {/* New pending files */}+ {pendingFiles.map((f, i) => (+ <div key={`new-${i}`} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '3px 8px', borderRadius: 8, background: 'var(--bg-secondary)', fontSize: 11, color: 'var(--text-muted)' }}>+ {f.name.length > 20 ? f.name.slice(0, 17) + '...' : f.name}+ <button type="button" onClick={() => setPendingFiles(prev => prev.filter((_, j) => j !== i))} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 0, display: 'flex' }}>+ <X size={10} />+ </button>+ </div>))}+ <label htmlFor="note-file-input"+ style={{ padding: '4px 10px', borderRadius: 8, border: '1px dashed var(--border-faint)', background: 'transparent', cursor: 'pointer', color: 'var(--text-faint)', fontSize: 11, fontFamily: FONT, display: 'inline-flex', alignItems: 'center', gap: 4 }}>+ <Plus size={11} /> {t('files.attach') || 'Add'}+ </label></div></div>@@ -361,7 +439,7 @@ function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {marginTop: 4,}}>- {submitting ? '...' : t('collab.notes.create')}+ {submitting ? '...' : isEdit ? t('collab.notes.save') : t('collab.notes.create')}</button></div></form>@@ -370,44 +448,171 @@ function NewNoteModal({ onClose, onSubmit, existingCategories, t }) {)}-// ── Note Card ───────────────────────────────────────────────────────────────-function NoteCard({ note, currentUser, onUpdate, onDelete, t }) {- const [hovered, setHovered] = useState(false)+function EditableCatName({ name, onRename }) {const [editing, setEditing] = useState(false)- const [editTitle, setEditTitle] = useState(note.title)- const [editContent, setEditContent] = useState(note.content || '')- const [saving, setSaving] = useState(false)-- const author = note.author || note.user || {}- const color = note.color || '#6366f1'+ const [value, setValue] = useState(name)+ const inputRef = useRef(null)- const handleStartEdit = useCallback(() => {- setEditTitle(note.title)- setEditContent(note.content || '')- setEditing(true)- }, [note.title, note.content])+ useEffect(() => { if (editing && inputRef.current) { inputRef.current.focus(); inputRef.current.select() } }, [editing])- const handleCancelEdit = useCallback(() => {+ const save = () => {setEditing(false)- setEditTitle(note.title)- setEditContent(note.content || '')- }, [note.title, note.content])+ if (value.trim() && value.trim() !== name) onRename(value.trim())+ else setValue(name)+ }- const handleSaveEdit = useCallback(async () => {- if (!editTitle.trim()) return- setSaving(true)- try {- await onUpdate(note.id, {- title: editTitle.trim(),- content: editContent.trim(),- })- setEditing(false)- } catch {- // error handled upstream- } finally {- setSaving(false)+ if (editing) {+ return <input ref={inputRef} value={value} onChange={e => setValue(e.target.value)}+ onBlur={save} onKeyDown={e => { if (e.key === 'Enter') save(); if (e.key === 'Escape') { setValue(name); setEditing(false) } }}+ style={{ flex: 1, fontSize: 13, fontWeight: 600, color: 'var(--text-primary)', border: '1px solid var(--border-primary)', borderRadius: 6, padding: '2px 8px', background: 'var(--bg-input)', fontFamily: 'inherit', outline: 'none' }} />+ }++ return (+ <span onClick={() => { setValue(name); setEditing(true) }}+ style={{ flex: 1, fontSize: 13, fontWeight: 600, color: 'var(--text-primary)', cursor: 'pointer', padding: '2px 0' }}+ title="Click to rename">+ {name}+ </span>+ )+}++// ── Category Settings Modal ──────────────────────────────────────────────────+function CategorySettingsModal({ onClose, categories, categoryColors, onSave, onRenameCategory, t }) {+ const [localColors, setLocalColors] = useState({ ...categoryColors })+ const [renames, setRenames] = useState({}) // { oldName: newName }+ const [newCatName, setNewCatName] = useState('')++ const handleColorChange = (cat, color) => {+ setLocalColors(prev => ({ ...prev, [cat]: color }))+ }++ const handleAddCategory = () => {+ if (!newCatName.trim() || localColors[newCatName.trim()]) return+ setLocalColors(prev => ({ ...prev, [newCatName.trim()]: NOTE_COLORS[Object.keys(prev).length % NOTE_COLORS.length].value }))+ setNewCatName('')+ }++ const handleRemoveCategory = (cat) => {+ setLocalColors(prev => { const n = { ...prev }; delete n[cat]; return n })+ }++ const handleRenameCategory = (oldName, newName) => {+ if (!newName.trim() || newName.trim() === oldName || localColors[newName.trim()]) return+ // Track rename for saving to DB later+ const originalName = Object.entries(renames).find(([, v]) => v === oldName)?.[0] || oldName+ setRenames(prev => ({ ...prev, [originalName]: newName.trim() }))+ setLocalColors(prev => {+ const n = {}+ for (const [k, v] of Object.entries(prev)) {+ n[k === oldName ? newName.trim() : k] = v+ }+ return n+ })+ }++ const handleSave = async () => {+ // Apply renames to notes in DB+ for (const [oldName, newName] of Object.entries(renames)) {+ if (oldName !== newName) await onRenameCategory(oldName, newName)}- }, [note.id, editTitle, editContent, onUpdate])+ await onSave(localColors)+ onClose()+ }++ // Merge existing categories from notes with saved colors+ const allCats = [...new Set([...categories, ...Object.keys(localColors)])]++ return ReactDOM.createPortal(+ <div style={{+ position: 'fixed', inset: 0, background: 'var(--overlay-bg, rgba(0,0,0,0.35))',+ backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',+ display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, padding: 16, fontFamily: FONT,+ }} onClick={onClose}>+ <div style={{+ background: 'var(--bg-card)', borderRadius: 16, width: '100%', maxWidth: 420,+ maxHeight: '80vh', overflow: 'auto', border: '1px solid var(--border-faint)',+ }} onClick={e => e.stopPropagation()}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px 12px', borderBottom: '1px solid var(--border-faint)' }}>+ <h3 style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)', margin: 0 }}>+ {t('collab.notes.categorySettings') || 'Category Settings'}+ </h3>+ <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 2, display: 'flex' }}>+ <X size={16} />+ </button>+ </div>++ {/* Categories list */}+ <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>+ {allCats.length === 0 && (+ <p style={{ fontSize: 12, color: 'var(--text-faint)', textAlign: 'center', padding: 16 }}>+ {t('collab.notes.noCategoriesYet') || 'No categories yet'}+ </p>+ )}+ {allCats.map(cat => (+ <div key={cat} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>+ {/* Color swatches */}+ <div style={{ display: 'flex', gap: 4 }}>+ {NOTE_COLORS.map(c => (+ <button key={c.value} onClick={() => handleColorChange(cat, c.value)} style={{+ width: 20, height: 20, borderRadius: 6, background: c.value, border: 'none', cursor: 'pointer', padding: 0,+ outline: (localColors[cat] || NOTE_COLORS[0].value) === c.value ? '2px solid var(--text-primary)' : '2px solid transparent',+ outlineOffset: 1, transition: 'transform 0.1s',+ transform: (localColors[cat] || NOTE_COLORS[0].value) === c.value ? 'scale(1.1)' : 'scale(1)',+ }} />+ ))}+ </div>+ {/* Category name — editable */}+ <EditableCatName name={cat} onRename={(newName) => handleRenameCategory(cat, newName)} />+ {/* Delete */}+ <button onClick={() => handleRemoveCategory(cat)} style={{+ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 3, display: 'flex',+ }}+ onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ <Trash2 size={13} />+ </button>+ </div>+ ))}++ {/* Add new */}+ <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>+ <input value={newCatName} onChange={e => setNewCatName(e.target.value)}+ onKeyDown={e => e.key === 'Enter' && handleAddCategory()}+ placeholder={t('collab.notes.newCategory')}+ style={{+ flex: 1, border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px',+ fontSize: 13, background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none',+ }} />+ <button onClick={handleAddCategory} disabled={!newCatName.trim()} style={{+ background: newCatName.trim() ? 'var(--accent)' : 'var(--border-primary)', color: 'var(--accent-text)',+ border: 'none', borderRadius: 10, padding: '8px 14px', cursor: newCatName.trim() ? 'pointer' : 'default',+ display: 'flex', alignItems: 'center', flexShrink: 0,+ }}>+ <Plus size={14} />+ </button>+ </div>++ {/* Save */}+ <button onClick={handleSave} style={{+ width: '100%', borderRadius: 99, padding: '9px 14px', background: 'var(--accent)', color: 'var(--accent-text)',+ fontSize: 13, fontWeight: 600, border: 'none', cursor: 'pointer', marginTop: 8,+ }}>+ {t('collab.notes.save')}+ </button>+ </div>+ </div>+ </div>,+ document.body+ )+}++// ── Note Card ───────────────────────────────────────────────────────────────+function NoteCard({ note, currentUser, onUpdate, onDelete, onEdit, onPreviewFile, getCategoryColor, tripId, t }) {+ const [hovered, setHovered] = useState(false)++ const author = note.author || note.user || { username: note.username, avatar: note.avatar_url || (note.avatar ? `/uploads/avatars/${note.avatar}` : null) }+ const color = getCategoryColor ? getCategoryColor(note.category) : (note.color || '#6366f1')const handleTogglePin = useCallback(() => {onUpdate(note.id, { pinned: !note.pinned })@@ -417,295 +622,151 @@ function NoteCard({ note, currentUser, onUpdate, onDelete, t }) {onDelete(note.id)}, [note.id, onDelete])- useEffect(() => {- if (!editing) {- setEditTitle(note.title)- setEditContent(note.content || '')- }- }, [note.title, note.content, editing])-return (<divonMouseEnter={() => setHovered(true)}onMouseLeave={() => setHovered(false)}style={{position: 'relative',- borderRadius: 10,- border: '1px solid var(--border-faint)',+ borderRadius: 12,overflow: 'hidden',- background: 'var(--bg-card)',+ border: `1px solid ${note.pinned ? color + '40' : color + '25'}`,+ background: note.pinned ? `${color}08` : 'var(--bg-card)',display: 'flex',flexDirection: 'column',fontFamily: FONT,+ transition: 'transform 0.12s, box-shadow 0.12s',+ ...(hovered ? { transform: 'translateY(-1px)', boxShadow: '0 4px 16px rgba(0,0,0,0.08)' } : {}),}}>- {/* Color stripe */}- <div style={{ height: 3, background: color, flexShrink: 0 }} />-- {/* Pin icon — top right */}- {!editing && (- <button- onClick={handleTogglePin}- title={note.pinned ? t('collab.notes.unpin') : t('collab.notes.pin')}- style={{- position: 'absolute',- top: 10,- right: 8,- background: 'none',- border: 'none',- cursor: 'pointer',- padding: 2,- borderRadius: 4,- display: 'flex',- color: 'var(--text-faint)',- opacity: note.pinned ? 1 : 0.5,- zIndex: 2,- }}- >- {note.pinned ? <Pin size={12} /> : <PinOff size={12} />}- </button>- )}-- {/* Hover actions — edit + delete */}+ {/* Header bar — like reservation cards */}<div style={{- position: 'absolute',- top: 10,- right: note.pinned ? 28 : 8,- display: 'flex',- gap: 2,- opacity: hovered && !editing ? 1 : 0,- pointerEvents: hovered && !editing ? 'auto' : 'none',- transition: 'opacity 0.15s',- zIndex: 3,+ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 10px',+ background: `${color}0d`,}}>- <button- onClick={handleStartEdit}- title={t('collab.notes.edit')}- style={{- width: 22,- height: 22,- borderRadius: 6,- border: 'none',- background: 'var(--bg-card)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: 'pointer',- color: 'var(--text-faint)',- }}- >- <Pencil size={11} />- </button>- <button- onClick={handleDelete}- title={t('collab.notes.delete')}- style={{- width: 22,- height: 22,- borderRadius: 6,- border: 'none',- background: 'var(--bg-card)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: 'pointer',- color: '#ef4444',- }}- >- <Trash2 size={11} />- </button>+ {!!note.pinned && <Pin size={9} color={color} style={{ flexShrink: 0 }} />}+ <span style={{ display: 'flex', alignItems: 'center', gap: 5, overflow: 'hidden', flex: 1, minWidth: 0 }}>+ <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {note.title}+ </span>+ {note.category && (+ <span style={{ fontSize: 8, fontWeight: 600, color, background: `${color}18`, padding: '2px 6px', borderRadius: 99, flexShrink: 0, letterSpacing: '0.02em', textTransform: 'uppercase' }}>+ {note.category}+ </span>+ )}+ </span>++ {/* Hover actions in header */}+ {(+ <div style={{+ display: 'flex', gap: 2,+ }}>+ <button onClick={handleTogglePin} title={note.pinned ? t('collab.notes.unpin') : t('collab.notes.pin')}+ style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}+ onMouseEnter={e => e.currentTarget.style.color = color}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ {note.pinned ? <PinOff size={10} /> : <Pin size={10} />}+ </button>+ <button onClick={() => onEdit?.(note)} title={t('collab.notes.edit')}+ style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}+ onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ <Pencil size={10} />+ </button>+ <button onClick={handleDelete} title={t('collab.notes.delete')}+ style={{ padding: 3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex' }}+ onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ <Trash2 size={10} />+ </button>+ <div style={{ width: 1, height: 12, background: 'var(--border-faint)', flexShrink: 0, marginLeft: 1, marginRight: 1 }} />+ {/* Author avatar */}+ <div style={{ position: 'relative', flexShrink: 0 }}+ onMouseEnter={e => { const tip = e.currentTarget.querySelector('[data-tip]'); if (tip) tip.style.opacity = '1' }}+ onMouseLeave={e => { const tip = e.currentTarget.querySelector('[data-tip]'); if (tip) tip.style.opacity = '0' }}>+ <UserAvatar user={author} size={16} />+ <div data-tip style={{+ position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)',+ marginBottom: 6, pointerEvents: 'none', opacity: 0, transition: 'opacity 0.12s',+ whiteSpace: 'nowrap', zIndex: 10,+ background: 'var(--bg-card)', color: 'var(--text-primary)',+ fontSize: 11, fontWeight: 500, padding: '5px 10px', borderRadius: 8,+ boxShadow: '0 4px 12px rgba(0,0,0,0.15)', border: '1px solid var(--border-faint)',+ }}>+ {author.username}+ </div>+ </div>+ </div>+ )}</div>{/* Card body */}<div style={{- padding: '10px 12px',+ padding: '8px 12px 10px',display: 'flex',flexDirection: 'column',gap: 4,flex: 1,}}>- {editing ? (- <>- <input- autoFocus- value={editTitle}- onChange={e => setEditTitle(e.target.value)}- placeholder={t('collab.notes.titlePlaceholder')}- onKeyDown={e => {- if (e.key === 'Escape') handleCancelEdit()- if (e.key === 'Enter' && e.metaKey) handleSaveEdit()- }}- style={{- width: '100%',- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- boxSizing: 'border-box',- }}- />- <textarea- value={editContent}- onChange={e => setEditContent(e.target.value)}- placeholder={t('collab.notes.contentPlaceholder')}- onKeyDown={e => {- if (e.key === 'Escape') handleCancelEdit()- if (e.key === 'Enter' && e.metaKey) handleSaveEdit()- }}- style={{- width: '100%',- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- boxSizing: 'border-box',- resize: 'vertical',- minHeight: 64,- lineHeight: 1.5,- }}- />- <div style={{- display: 'flex',- gap: 6,- justifyContent: 'flex-end',- marginTop: 4,- }}>- <button- type="button"- onClick={handleCancelEdit}- style={{- display: 'inline-flex',- alignItems: 'center',- gap: 3,- borderRadius: 99,- padding: '4px 10px',- border: '1px solid var(--border-primary)',- background: 'transparent',- color: 'var(--text-secondary)',- fontSize: 11,- fontWeight: 500,- fontFamily: FONT,- cursor: 'pointer',- }}- >- <X size={10} />- {t('collab.notes.cancel')}- </button>- <button- type="button"- onClick={handleSaveEdit}- disabled={!editTitle.trim() || saving}- style={{- display: 'inline-flex',- alignItems: 'center',- gap: 3,- borderRadius: 99,- padding: '4px 10px',- border: 'none',- background: 'var(--accent)',- color: 'var(--accent-text)',- fontSize: 11,- fontWeight: 600,- fontFamily: FONT,- cursor: 'pointer',- }}- >- <Check size={10} />- {saving ? '...' : t('collab.notes.save')}- </button>- </div>- </>- ) : (- <>- {/* Title */}- <div style={{- fontSize: 13,- fontWeight: 600,- color: 'var(--text-primary)',- lineHeight: 1.35,- paddingRight: 24,- wordBreak: 'break-word',- fontFamily: FONT,- }}>- {note.title}- </div>-- {/* Content — 3 line clamp */}+ <div style={{ display: 'flex', gap: 8 }}>+ <div style={{ flex: 1, minWidth: 0 }}>{note.content && (<p style={{- fontSize: 11,- color: 'var(--text-muted)',- lineHeight: 1.5,- margin: 0,- display: '-webkit-box',- WebkitLineClamp: 3,- WebkitBoxOrient: 'vertical',- overflow: 'hidden',- wordBreak: 'break-word',- fontFamily: FONT,+ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, margin: 0,+ display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',+ overflow: 'hidden', wordBreak: 'break-word', fontFamily: FONT,}}>{note.content}</p>)}-- {/* Category badge */}- {note.category && (- <div style={{ marginTop: 2 }}>- <span style={{- display: 'inline-block',- fontSize: 9,- padding: '1px 6px',- borderRadius: 4,- background: 'var(--bg-tertiary)',- color: 'var(--text-faint)',- fontWeight: 600,- fontFamily: FONT,- textTransform: 'uppercase',- letterSpacing: '0.03em',- }}>- {note.category}- </span>- </div>- )}-- {/* Author row */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: 4,- marginTop: 6,- }}>- <UserAvatar user={author} size={14} />- <span style={{- fontSize: 9,- color: 'var(--text-faint)',- fontFamily: FONT,- whiteSpace: 'nowrap',- overflow: 'hidden',- textOverflow: 'ellipsis',- }}>- {author.username || '?'}- </span>- <span style={{- fontSize: 9,- color: 'var(--text-faint)',- fontFamily: FONT,- marginLeft: 'auto',- flexShrink: 0,- }}>- {formatTimestamp(note.updated_at || note.created_at)}- </span>- </div>- </>- )}+ </div>+ {/* Right: website + attachment thumbnails */}+ {(note.website || note.attachments?.length > 0) && (+ <div style={{ display: 'flex', gap: 6, flexShrink: 0, alignItems: 'flex-start' }}>+ {/* Website */}+ {note.website && (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>+ <span style={{ fontSize: 7, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.3 }}>Link</span>+ <WebsiteThumbnail url={note.website} tripId={tripId} color={color} />+ </div>+ )}+ {/* Files */}+ {(note.attachments || []).length > 0 && (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>+ <span style={{ fontSize: 7, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.3 }}>{t('files.title')}</span>+ <div style={{ display: 'flex', gap: 4 }}>+ {(note.attachments || []).slice(0, note.website ? 1 : 2).map(a => {+ const isImage = a.mime_type?.startsWith('image/')+ const ext = (a.original_name || '').split('.').pop()?.toUpperCase() || '?'+ return isImage ? (+ <img key={a.id} src={a.url} alt={a.original_name}+ style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 8, cursor: 'pointer', transition: 'transform 0.12s, box-shadow 0.12s' }}+ onClick={() => onPreviewFile?.(a)}+ onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.08)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}+ onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }} />+ ) : (+ <div key={a.id} title={a.original_name} onClick={() => onPreviewFile?.(a)}+ style={{+ width: 48, height: 48, borderRadius: 8, cursor: 'pointer',+ background: a.mime_type === 'application/pdf' ? '#ef44441a' : 'var(--bg-secondary)',+ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1,+ transition: 'transform 0.12s, box-shadow 0.12s',+ }}+ onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.08)'; e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)' }}+ onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = 'none' }}>+ <span style={{ fontSize: 9, fontWeight: 700, color: a.mime_type === 'application/pdf' ? '#ef4444' : 'var(--text-muted)', letterSpacing: 0.3 }}>{ext}</span>+ </div>+ )+ })}+ {(note.attachments?.length || 0) > (note.website ? 1 : 2) && (+ <span style={{ fontSize: 8, color: 'var(--text-faint)', textAlign: 'center' }}>+{(note.attachments?.length || 0) - (note.website ? 1 : 2)}</span>+ )}+ </div>+ </div>+ )}+ </div>+ )}+ </div></div></div>)@@ -717,8 +778,35 @@ export default function CollabNotes({ tripId, currentUser }) {const [notes, setNotes] = useState([])const [loading, setLoading] = useState(true)const [showNewModal, setShowNewModal] = useState(false)+ const [editingNote, setEditingNote] = useState(null)+ const [previewFile, setPreviewFile] = useState(null)+ const [showSettings, setShowSettings] = useState(false)const [activeCategory, setActiveCategory] = useState(null)+ // Empty categories (no notes yet) stored in localStorage+ const [emptyCategories, setEmptyCategories] = useState(() => {+ try { return JSON.parse(localStorage.getItem(`collab-cats-${tripId}`)) || {} } catch { return {} }+ })+ const saveEmptyCategories = (map) => {+ setEmptyCategories(map)+ localStorage.setItem(`collab-cats-${tripId}`, JSON.stringify(map))+ }++ // Category colors: from notes first, then from empty categories+ const categoryColors = useMemo(() => {+ const map = { ...emptyCategories }+ for (const n of notes) {+ if (n.category && n.color) map[n.category] = n.color+ }+ return map+ }, [notes, emptyCategories])++ const getCategoryColor = (cat) => {+ if (!cat) return NOTE_COLORS[0].value+ if (categoryColors[cat]) return categoryColors[cat]+ return NOTE_COLORS[Object.keys(categoryColors).length % NOTE_COLORS.length].value+ }+// ── Load notes on mount ──useEffect(() => {if (!tripId) return@@ -761,17 +849,34 @@ export default function CollabNotes({ tripId, currentUser }) {// ── Actions ──const handleCreateNote = useCallback(async (data) => {+ const pendingFiles = data._pendingFiles || []+ delete data._pendingFilesconst created = await collabApi.createNote(tripId, data)if (created) {+ const note = created.note || created+ // Upload pending files+ if (pendingFiles.length > 0 && note.id) {+ for (const file of pendingFiles) {+ const fd = new FormData()+ fd.append('file', file)+ try { await collabApi.uploadNoteFile(tripId, note.id, fd) } catch {}+ }+ // Reload note with attachments+ const fresh = await collabApi.getNotes(tripId)+ if (fresh?.notes) setNotes(fresh.notes)+ window.dispatchEvent(new Event('collab-files-changed'))+ return+ }setNotes(prev => {- if (prev.some(n => n.id === created.id)) return prev- return [created, ...prev]+ if (prev.some(n => n.id === note.id)) return prev+ return [note, ...prev]})}}, [tripId])const handleUpdateNote = useCallback(async (noteId, data) => {- const updated = await collabApi.updateNote(tripId, noteId, data)+ const result = await collabApi.updateNote(tripId, noteId, data)+ const updated = result?.note || resultif (updated) {setNotes(prev =>prev.map(n => (n.id === noteId ? { ...n, ...updated } : n))@@ -779,9 +884,52 @@ export default function CollabNotes({ tripId, currentUser }) {}}, [tripId])+ const saveCategoryColors = useCallback(async (newMap) => {+ // Update notes with changed colors+ for (const [cat, color] of Object.entries(newMap)) {+ const notesInCat = notes.filter(n => n.category === cat)+ if (notesInCat.length > 0 && categoryColors[cat] !== color) {+ for (const n of notesInCat) {+ await handleUpdateNote(n.id, { color })+ }+ }+ }+ // Save all categories (including empty ones) to localStorage+ const emptyCats = {}+ for (const [cat, color] of Object.entries(newMap)) {+ if (!notes.some(n => n.category === cat)) {+ emptyCats[cat] = color+ }+ }+ saveEmptyCategories(emptyCats)+ }, [categoryColors, notes, handleUpdateNote])++ const handleEditSubmit = useCallback(async (data) => {+ if (!editingNote) return+ const pendingFiles = data._pendingFiles || []+ delete data._pendingFiles+ await handleUpdateNote(editingNote.id, data)+ if (pendingFiles.length > 0) {+ for (const file of pendingFiles) {+ const fd = new FormData()+ fd.append('file', file)+ try { await collabApi.uploadNoteFile(tripId, editingNote.id, fd) } catch {}+ }+ const fresh = await collabApi.getNotes(tripId)+ if (fresh?.notes) setNotes(fresh.notes)+ window.dispatchEvent(new Event('collab-files-changed'))+ }+ }, [editingNote, tripId, handleUpdateNote])++ const handleDeleteNoteFile = useCallback(async (noteId, fileId) => {+ try { await collabApi.deleteNoteFile(tripId, noteId, fileId) } catch {}+ window.dispatchEvent(new Event('collab-files-changed'))+ }, [tripId])+const handleDeleteNote = useCallback(async (noteId) => {await collabApi.deleteNote(tripId, noteId)setNotes(prev => prev.filter(n => n.id !== noteId))+ window.dispatchEvent(new Event('collab-files-changed'))}, [tripId])// ── Derived data ──@@ -852,40 +1000,37 @@ export default function CollabNotes({ tripId, currentUser }) {display: 'flex',alignItems: 'center',justifyContent: 'space-between',- padding: '12px 16px',- borderBottom: '1px solid var(--border-faint)',+ padding: '10px 16px',flexShrink: 0,}}><h3 style={{- fontSize: 14,- fontWeight: 700,- color: 'var(--text-primary)',+ fontSize: 12,+ fontWeight: 600,+ color: 'var(--text-muted)',margin: 0,fontFamily: FONT,+ letterSpacing: 0.3,+ textTransform: 'uppercase',+ display: 'flex',+ alignItems: 'center',+ gap: 7,}}>+ <StickyNote size={14} color="var(--text-faint)" />{t('collab.notes.title')}</h3>- <button- onClick={() => setShowNewModal(true)}- style={{- display: 'inline-flex',- alignItems: 'center',- gap: 4,- borderRadius: 99,- padding: '7px 14px',- background: 'var(--accent)',- color: 'var(--accent-text)',- fontSize: 12,- fontWeight: 600,- fontFamily: FONT,- border: 'none',- cursor: 'pointer',- whiteSpace: 'nowrap',- }}- >- <Plus size={13} />- {t('collab.notes.new')}- </button>+ <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>+ <button onClick={() => setShowSettings(true)} title={t('collab.notes.categorySettings') || 'Categories'}+ style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, borderRadius: 8, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--text-faint)', transition: 'color 0.12s' }}+ onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ <Settings size={14} />+ </button>+ <button onClick={() => setShowNewModal(true)}+ style={{ display: 'inline-flex', alignItems: 'center', gap: 4, borderRadius: 99, padding: '6px 12px', background: 'var(--accent)', color: 'var(--accent-text)', fontSize: 11, fontWeight: 600, fontFamily: FONT, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap' }}>+ <Plus size={12} />+ {t('collab.notes.new')}+ </button>+ </div></div>{/* ── Category filter pills ── */}@@ -970,6 +1115,7 @@ export default function CollabNotes({ tripId, currentUser }) {justifyContent: 'center',padding: '48px 20px',textAlign: 'center',+ height: '100%',}}><Pencil size={36} color="var(--text-faint)" style={{ marginBottom: 12 }} /><div style={{@@ -990,10 +1136,10 @@ export default function CollabNotes({ tripId, currentUser }) {</div></div>) : (- /* ── Notes list — single column ── */+ /* ── Notes grid — 2 columns ── */<div style={{- display: 'flex',- flexDirection: 'column',+ display: 'grid',+ gridTemplateColumns: window.innerWidth < 768 ? '1fr' : 'repeat(2, 1fr)',gap: 8,}}>{sortedNotes.map(note => (@@ -1003,6 +1149,10 @@ export default function CollabNotes({ tripId, currentUser }) {currentUser={currentUser}onUpdate={handleUpdateNote}onDelete={handleDeleteNote}+ onEdit={setEditingNote}+ onPreviewFile={setPreviewFile}+ getCategoryColor={getCategoryColor}+ tripId={tripId}t={t}/>))}@@ -1012,10 +1162,48 @@ export default function CollabNotes({ tripId, currentUser }) {{/* ── New Note Modal ── */}{showNewModal && (- <NewNoteModal+ <NoteFormModalonClose={() => setShowNewModal(false)}onSubmit={handleCreateNote}existingCategories={categories}+ categoryColors={categoryColors}+ getCategoryColor={getCategoryColor}+ t={t}+ />+ )}++ {/* ── Edit Note Modal ── */}+ {editingNote && (+ <NoteFormModal+ note={editingNote}+ tripId={tripId}+ onClose={() => setEditingNote(null)}+ onSubmit={handleEditSubmit}+ onDeleteFile={handleDeleteNoteFile}+ existingCategories={categories}+ categoryColors={categoryColors}+ getCategoryColor={getCategoryColor}+ t={t}+ />+ )}++ {/* ── File Preview ── */}+ <FilePreviewPortal file={previewFile} onClose={() => setPreviewFile(null)} />++ {/* ── Category Settings Modal ── */}+ {showSettings && (+ <CategorySettingsModal+ onClose={() => setShowSettings(false)}+ categories={categories}+ categoryColors={categoryColors}+ onSave={saveCategoryColors}+ onRenameCategory={async (oldName, newName) => {+ // Update all notes with this category in DB+ const toUpdate = notes.filter(n => n.category === oldName)+ for (const n of toUpdate) {+ await handleUpdateNote(n.id, { category: newName })+ }+ }}t={t}/>)}diff --git a/client/src/components/Collab/CollabPanel.jsx b/client/src/components/Collab/CollabPanel.jsxindex 42b67ff32..c640c1755 100644--- a/client/src/components/Collab/CollabPanel.jsx+++ b/client/src/components/Collab/CollabPanel.jsx@@ -1,34 +1,101 @@-import React from 'react'+import React, { useState, useEffect } from 'react'import { useAuthStore } from '../../store/authStore'+import { useTranslation } from '../../i18n'+import { MessageCircle, StickyNote, BarChart3, Sparkles } from 'lucide-react'import CollabChat from './CollabChat'import CollabNotes from './CollabNotes'import CollabPolls from './CollabPolls'+import WhatsNextWidget from './WhatsNextWidget'-export default function CollabPanel({ tripId }) {+function useIsDesktop(breakpoint = 1024) {+ const [isDesktop, setIsDesktop] = useState(window.innerWidth >= breakpoint)+ useEffect(() => {+ const check = () => setIsDesktop(window.innerWidth >= breakpoint)+ window.addEventListener('resize', check)+ return () => window.removeEventListener('resize', check)+ }, [breakpoint])+ return isDesktop+}++const card = {+ display: 'flex', flexDirection: 'column',+ background: 'var(--bg-card)', borderRadius: 16, border: '1px solid var(--border-faint)',+ overflow: 'hidden', minHeight: 0,+}++export default function CollabPanel({ tripId, tripMembers = [] }) {const { user } = useAuthStore()+ const { t } = useTranslation()+ const [mobileTab, setMobileTab] = useState('chat')+ const isDesktop = useIsDesktop()- return (- <div style={{ height: '100%', overflowY: 'auto', overscrollBehavior: 'contain', fontFamily: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif" }}>- <div style={{ maxWidth: 1400, margin: '0 auto', padding: '16px' }}>- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4" style={{ alignItems: 'start' }}>+ const tabs = [+ { id: 'chat', label: t('collab.tabs.chat') || 'Chat', icon: MessageCircle },+ { id: 'notes', label: t('collab.tabs.notes') || 'Notes', icon: StickyNote },+ { id: 'polls', label: t('collab.tabs.polls') || 'Polls', icon: BarChart3 },+ { id: 'next', label: t('collab.whatsNext.title') || "What's Next", icon: Sparkles },+ ]- {/* Chat — takes 1 column, full height */}- <div style={{ background: 'var(--bg-card)', borderRadius: 16, border: '1px solid var(--border-faint)', overflow: 'hidden', height: 500 }}>- <CollabChat tripId={tripId} currentUser={user} />- </div>+ if (isDesktop) {+ return (+ <div style={{ height: '100%', display: 'flex', gap: 12, padding: 12, overflow: 'hidden', minHeight: 0 }}>+ {/* Chat — left, fixed width */}+ <div style={{ ...card, flex: '0 0 380px' }}>+ <CollabChat tripId={tripId} currentUser={user} />+ </div>- {/* Notes — takes 1 column */}- <div style={{ background: 'var(--bg-card)', borderRadius: 16, border: '1px solid var(--border-faint)', overflow: 'hidden', maxHeight: 500, display: 'flex', flexDirection: 'column' }}>+ {/* Right column: Notes top, Polls + What's Next bottom */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 12, overflow: 'hidden', minHeight: 0 }}>+ {/* Notes — top */}+ <div style={{ ...card, flex: 1 }}><CollabNotes tripId={tripId} currentUser={user} /></div>- {/* Polls — takes 1 column */}- <div style={{ background: 'var(--bg-card)', borderRadius: 16, border: '1px solid var(--border-faint)', overflow: 'hidden', maxHeight: 500, display: 'flex', flexDirection: 'column' }}>- <CollabPolls tripId={tripId} currentUser={user} />+ {/* Polls + What's Next — bottom row */}+ <div style={{ flex: 1, display: 'flex', gap: 12, overflow: 'hidden', minHeight: 0 }}>+ <div style={{ ...card, flex: 1 }}>+ <CollabPolls tripId={tripId} currentUser={user} />+ </div>+ <div style={{ ...card, flex: 1 }}>+ <WhatsNextWidget tripMembers={tripMembers} />+ </div></div>-</div></div>+ )+ }++ // Mobile: tab bar + single panel+ return (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'absolute', inset: 0 }}>+ <div style={{+ display: 'flex', gap: 2, padding: '8px 12px', borderBottom: '1px solid var(--border-faint)',+ background: 'var(--bg-card)', flexShrink: 0,+ }}>+ {tabs.map(tab => {+ const Icon = tab.icon+ const active = mobileTab === tab.id+ return (+ <button key={tab.id} onClick={() => setMobileTab(tab.id)} style={{+ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,+ padding: '8px 0', borderRadius: 10, border: 'none', cursor: 'pointer',+ background: active ? 'var(--accent)' : 'transparent',+ color: active ? 'var(--accent-text)' : 'var(--text-muted)',+ fontSize: 11, fontWeight: 600, fontFamily: 'inherit',+ transition: 'all 0.15s',+ }}>+ {tab.label}+ </button>+ )+ })}+ </div>++ <div style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>+ {mobileTab === 'chat' && <CollabChat tripId={tripId} currentUser={user} />}+ {mobileTab === 'notes' && <CollabNotes tripId={tripId} currentUser={user} />}+ {mobileTab === 'polls' && <CollabPolls tripId={tripId} currentUser={user} />}+ {mobileTab === 'next' && <WhatsNextWidget tripMembers={tripMembers} />}+ </div></div>)}diff --git a/client/src/components/Collab/CollabPolls.jsx b/client/src/components/Collab/CollabPolls.jsxindex d2ece2eea..fff4d72bb 100644--- a/client/src/components/Collab/CollabPolls.jsx+++ b/client/src/components/Collab/CollabPolls.jsx@@ -3,13 +3,10 @@ import { Plus, Trash2, X, Check, BarChart3, Lock, Clock } from 'lucide-react'import { collabApi } from '../../api/client'import { addListener, removeListener } from '../../api/websocket'import { useTranslation } from '../../i18n'--// ── Constants ────────────────────────────────────────────────────────────────+import ReactDOM from 'react-dom'const FONT = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif"-// ── Helpers ──────────────────────────────────────────────────────────────────-function timeRemaining(deadline) {if (!deadline) return nullconst diff = new Date(deadline).getTime() - Date.now()@@ -28,1019 +25,398 @@ function isExpired(deadline) {}function totalVotes(poll) {- if (!poll.options) return 0- return poll.options.reduce((s, o) => s + (o.voters?.length || 0), 0)+ return (poll.options || []).reduce((s, o) => s + (o.voters?.length || 0), 0)}-// ── Voter Avatars ────────────────────────────────────────────────────────────--function VoterAvatars({ voters = [] }) {- const MAX = 4- const shown = voters.slice(0, MAX)- const extra = voters.length - MAX-- if (!voters.length) return null-- return (- <div style={{ display: 'flex', alignItems: 'center', marginTop: 3, minHeight: 14 }}>- {shown.map((v, i) => (- <div- key={v.id || i}- title={v.username}- style={{- width: 14,- height: 14,- borderRadius: '50%',- border: '1.5px solid var(--bg-primary)',- marginLeft: i === 0 ? 0 : -4,- overflow: 'hidden',- background: 'var(--bg-tertiary)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- fontSize: 7,- fontWeight: 700,- fontFamily: FONT,- color: 'var(--text-secondary)',- flexShrink: 0,- zIndex: MAX - i,- position: 'relative',- }}- >- {v.avatar ? (- <img- src={v.avatar}- alt=""- style={{ width: '100%', height: '100%', objectFit: 'cover' }}- />- ) : (- (v.username || '?')[0].toUpperCase()- )}- </div>- ))}- {extra > 0 && (- <span- style={{- fontSize: 9,- fontFamily: FONT,- color: 'var(--text-faint)',- marginLeft: 3,- fontWeight: 600,- }}- >- +{extra}- </span>- )}- </div>- )-}--// ── Option Bar ───────────────────────────────────────────────────────────────--function OptionBar({ option, index, poll, currentUser, onVote, isClosed }) {- const total = totalVotes(poll)- const count = option.voters?.length || 0- const pct = total > 0 ? Math.round((count / total) * 100) : 0- const voted = option.voters?.some((v) => v.id === currentUser.id)- const canVote = !isClosed && !poll.is_closed-- return (- <div- onClick={() => canVote && onVote(poll.id, index)}- style={{- position: 'relative',- width: '100%',- padding: '8px 12px',- borderRadius: 8,- border: voted- ? '1px solid var(--accent)'- : '1px solid var(--border-faint)',- overflow: 'hidden',- cursor: canVote ? 'pointer' : 'default',- marginTop: 4,- boxSizing: 'border-box',- fontFamily: FONT,- }}- onMouseEnter={(e) => {- if (canVote) e.currentTarget.style.borderColor = 'var(--accent)'- }}- onMouseLeave={(e) => {- if (canVote && !voted)- e.currentTarget.style.borderColor = 'var(--border-faint)'- }}- >- {/* Vote fill bar */}- <div- style={{- position: 'absolute',- left: 0,- top: 0,- bottom: 0,- width: `${pct}%`,- background: 'var(--accent)',- opacity: voted ? 0.15 : 0.1,- transition: 'width 0.3s',- pointerEvents: 'none',- }}- />-- {/* Content row */}- <div- style={{- position: 'relative',- zIndex: 1,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- gap: 8,- }}- >- <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 1, minWidth: 0 }}>- {voted && (- <Check- size={12}- style={{ color: 'var(--accent)', flexShrink: 0 }}- strokeWidth={2.5}- />- )}- <span- style={{- fontSize: 12,- fontWeight: voted ? 600 : 400,- color: 'var(--text-primary)',- fontFamily: FONT,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',- }}- >- {option.text}- </span>- </div>-- <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>- <span- style={{- fontSize: 11,- color: 'var(--text-muted)',- fontFamily: FONT,- fontVariantNumeric: 'tabular-nums',- }}- >- {count}- </span>- <span- style={{- fontSize: 11,- fontWeight: 600,- color: 'var(--text-primary)',- fontFamily: FONT,- fontVariantNumeric: 'tabular-nums',- minWidth: 28,- textAlign: 'right',- }}- >- {pct}%- </span>- </div>- </div>-- {/* Voter avatars */}- {option.voters?.length > 0 && (- <div style={{ position: 'relative', zIndex: 1 }}>- <VoterAvatars voters={option.voters} />- </div>- )}- </div>- )-}--// ── Create Poll Form ─────────────────────────────────────────────────────────--function CreatePollForm({ onSubmit, onCancel, t }) {+// ── Create Poll Modal ────────────────────────────────────────────────────────+function CreatePollModal({ onClose, onCreate, t }) {const [question, setQuestion] = useState('')const [options, setOptions] = useState(['', ''])- const [multipleChoice, setMultipleChoice] = useState(false)- const [deadline, setDeadline] = useState('')+ const [multiChoice, setMultiChoice] = useState(false)const [submitting, setSubmitting] = useState(false)- const canSubmit =- question.trim().length > 0 &&- options.filter((o) => o.trim()).length >= 2 &&- !submitting-- const addOption = () => setOptions((prev) => [...prev, ''])-- const removeOption = (i) => {- if (options.length <= 2) return- setOptions((prev) => prev.filter((_, idx) => idx !== i))- }+ const addOption = () => setOptions(prev => [...prev, ''])+ const removeOption = (i) => setOptions(prev => prev.filter((_, j) => j !== i))+ const updateOption = (i, v) => setOptions(prev => prev.map((o, j) => j === i ? v : o))- const updateOption = (i, val) =>- setOptions((prev) => prev.map((o, idx) => (idx === i ? val : o)))+ const canSubmit = question.trim() && options.filter(o => o.trim()).length >= 2 && !submittingconst handleSubmit = async (e) => {e.preventDefault()if (!canSubmit) returnsetSubmitting(true)try {- await onSubmit({- question: question.trim(),- options: options.filter((o) => o.trim()).map((o) => o.trim()),- multiple_choice: multipleChoice,- deadline: deadline || undefined,- })- setQuestion('')- setOptions(['', ''])- setMultipleChoice(false)- setDeadline('')- } finally {- setSubmitting(false)- }+ await onCreate({ question: question.trim(), options: options.filter(o => o.trim()), multiple_choice: multiChoice })+ onClose()+ } catch {} finally { setSubmitting(false) }}- return (- <form- onSubmit={handleSubmit}- style={{- background: 'var(--bg-secondary)',- borderRadius: 10,- padding: 12,- marginBottom: 8,- fontFamily: FONT,- }}- >- {/* Question */}- <input- type="text"- value={question}- onChange={(e) => setQuestion(e.target.value)}- placeholder={t('collab.polls.question')}- style={{- width: '100%',- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- boxSizing: 'border-box',- }}- onFocus={(e) => (e.target.style.borderColor = 'var(--accent)')}- onBlur={(e) => (e.target.style.borderColor = 'var(--border-primary)')}- autoFocus- />-- {/* Options */}- <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>- {options.map((opt, i) => (- <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>- <input- type="text"- value={opt}- onChange={(e) => updateOption(i, e.target.value)}- placeholder={`${t('collab.polls.addOption').replace('+', '').trim()} ${i + 1}`}- style={{- flex: 1,- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- boxSizing: 'border-box',- }}- onFocus={(e) => (e.target.style.borderColor = 'var(--accent)')}- onBlur={(e) => (e.target.style.borderColor = 'var(--border-primary)')}- />- {options.length > 2 && (- <button- type="button"- onClick={() => removeOption(i)}- style={{- background: 'none',- border: 'none',- cursor: 'pointer',- padding: 4,- color: 'var(--text-faint)',- display: 'flex',- alignItems: 'center',- fontFamily: FONT,- }}- onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--danger, #ef4444)')}- onMouseLeave={(e) => (e.currentTarget.style.color = 'var(--text-faint)')}- >- <X size={13} />- </button>- )}+ return ReactDOM.createPortal(+ <div style={{ position: 'fixed', inset: 0, background: 'var(--overlay-bg, rgba(0,0,0,0.35))', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, padding: 16, fontFamily: FONT }} onClick={onClose}>+ <form style={{ background: 'var(--bg-card)', borderRadius: 16, width: '100%', maxWidth: 400, maxHeight: '90vh', overflow: 'auto', border: '1px solid var(--border-faint)' }} onClick={e => e.stopPropagation()} onSubmit={handleSubmit}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px 12px', borderBottom: '1px solid var(--border-faint)' }}>+ <h3 style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-primary)', margin: 0 }}>{t('collab.polls.new')}</h3>+ <button type="button" onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', padding: 2, display: 'flex' }}><X size={16} /></button>+ </div>+ <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>+ {/* Question */}+ <div>+ <div style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>{t('collab.polls.question')}</div>+ <input autoFocus value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder') || 'Ask a question...'} style={{ width: '100%', border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px', fontSize: 13, background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} /></div>- ))}- </div>- {/* + Add option link */}- <div- onClick={addOption}- style={{- fontSize: 11,- color: 'var(--text-muted)',- cursor: 'pointer',- fontFamily: FONT,- padding: '6px 0 2px',- display: 'flex',- alignItems: 'center',- gap: 3,- }}- >- <Plus size={11} />- {t('collab.polls.addOption')}- </div>-- {/* Settings row */}- <div- style={{- display: 'flex',- alignItems: 'center',- gap: 16,- marginTop: 10,- flexWrap: 'wrap',- }}- >- {/* Multiple choice toggle */}- <label- style={{- display: 'flex',- alignItems: 'center',- gap: 6,- fontSize: 12,- color: 'var(--text-secondary)',- cursor: 'pointer',- userSelect: 'none',- fontFamily: FONT,- }}- >- <div- onClick={() => setMultipleChoice(!multipleChoice)}- style={{- width: 14,- height: 14,- borderRadius: 4,- border: multipleChoice- ? '1px solid var(--accent)'- : '1px solid var(--border-primary)',- background: multipleChoice ? 'var(--accent)' : 'transparent',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- cursor: 'pointer',- flexShrink: 0,- }}- >- {multipleChoice && <Check size={9} style={{ color: '#fff' }} strokeWidth={3} />}+ {/* Options */}+ <div>+ <div style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>{t('collab.polls.options')}</div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>+ {options.map((opt, i) => (+ <div key={i} style={{ display: 'flex', gap: 6, alignItems: 'center' }}>+ <input value={opt} onChange={e => updateOption(i, e.target.value)} placeholder={`${t('collab.polls.option')} ${i + 1}`}+ style={{ flex: 1, border: '1px solid var(--border-primary)', borderRadius: 10, padding: '8px 12px', fontSize: 13, background: 'var(--bg-input)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none' }} />+ {options.length > 2 && (+ <button type="button" onClick={() => removeOption(i)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', padding: 2 }}><X size={14} /></button>+ )}+ </div>+ ))}+ <button type="button" onClick={addOption} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 12px', borderRadius: 10, border: '1px dashed var(--border-faint)', background: 'transparent', cursor: 'pointer', color: 'var(--text-faint)', fontSize: 12, fontFamily: FONT }}>+ <Plus size={12} /> {t('collab.polls.addOption')}+ </button>+ </div></div>- {t('collab.polls.multipleChoice')}- </label>- {/* Deadline */}- <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>- <Clock size={12} style={{ color: 'var(--text-faint)' }} />- <input- type="datetime-local"- value={deadline}- onChange={(e) => setDeadline(e.target.value)}- style={{- border: '1px solid var(--border-primary)',- borderRadius: 10,- padding: '8px 12px',- fontSize: 13,- background: 'var(--bg-input)',- color: 'var(--text-primary)',- fontFamily: 'inherit',- outline: 'none',- }}- />+ {/* Multi choice toggle */}+ <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>+ <div onClick={() => setMultiChoice(!multiChoice)} style={{+ width: 36, height: 20, borderRadius: 10, padding: 2, cursor: 'pointer',+ background: multiChoice ? '#007AFF' : 'var(--border-primary)', transition: 'background 0.2s',+ display: 'flex', alignItems: 'center',+ }}>+ <div style={{ width: 16, height: 16, borderRadius: '50%', background: '#fff', transition: 'transform 0.2s', transform: multiChoice ? 'translateX(16px)' : 'translateX(0)' }} />+ </div>+ <span style={{ fontSize: 12, color: 'var(--text-muted)', fontFamily: FONT }}>{t('collab.polls.multiChoice')}</span>+ </label>++ {/* Submit */}+ <button type="submit" disabled={!canSubmit} style={{+ width: '100%', borderRadius: 99, padding: '9px 14px', background: canSubmit ? 'var(--accent)' : 'var(--border-primary)',+ color: canSubmit ? 'var(--accent-text)' : 'var(--text-faint)', fontSize: 13, fontWeight: 600, border: 'none', cursor: canSubmit ? 'pointer' : 'default', fontFamily: FONT,+ }}>+ {submitting ? '...' : t('collab.polls.create')}+ </button></div>- </div>+ </form>+ </div>,+ document.body+ )+}- {/* Actions */}- <div- style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'flex-end',- gap: 8,- marginTop: 12,+// ── Voter Chip with custom tooltip ────────────────────────────────────────────+function VoterChip({ voter, offset }) {+ const [hover, setHover] = useState(false)+ const ref = React.useRef(null)+ const [pos, setPos] = useState({ top: 0, left: 0 })++ return (+ <>+ <div ref={ref}+ onMouseEnter={() => {+ if (ref.current) {+ const rect = ref.current.getBoundingClientRect()+ setPos({ top: rect.top - 6, left: rect.left + rect.width / 2 })+ }+ setHover(true)}}- >- <button- type="button"- onClick={onCancel}- style={{- background: 'none',- border: '1px solid var(--border-primary)',- borderRadius: 99,- padding: '5px 14px',- fontSize: 12,- fontWeight: 500,- color: 'var(--text-secondary)',- cursor: 'pointer',- fontFamily: FONT,- }}- onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--bg-tertiary)')}- onMouseLeave={(e) => (e.currentTarget.style.background = 'none')}- >- {t('common.cancel', 'Cancel')}- </button>- <button- type="submit"- disabled={!canSubmit}- style={{- background: canSubmit ? 'var(--accent)' : 'var(--bg-tertiary)',- border: 'none',- borderRadius: 99,- padding: '5px 14px',- fontSize: 12,- fontWeight: 600,- color: canSubmit ? '#fff' : 'var(--text-faint)',- cursor: canSubmit ? 'pointer' : 'not-allowed',- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 4,- }}- onMouseEnter={(e) => {- if (canSubmit) e.currentTarget.style.opacity = '0.85'- }}- onMouseLeave={(e) => {- e.currentTarget.style.opacity = '1'- }}- >- <BarChart3 size={12} />- {t('collab.polls.create')}- </button>+ onMouseLeave={() => setHover(false)}+ style={{+ width: 18, height: 18, borderRadius: '50%', background: 'var(--bg-tertiary)',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ fontSize: 7, fontWeight: 700, color: 'var(--text-muted)', overflow: 'hidden',+ border: '1.5px solid var(--bg-card)', marginLeft: offset ? -5 : 0, flexShrink: 0,+ }}>+ {voter.avatar_url ? <img src={voter.avatar_url} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : (voter.username || '?')[0].toUpperCase()}</div>- </form>+ {hover && ReactDOM.createPortal(+ <div style={{+ position: 'fixed', top: pos.top, left: pos.left, transform: 'translate(-50%, -100%)',+ pointerEvents: 'none', zIndex: 10000, whiteSpace: 'nowrap',+ background: 'var(--bg-card)', color: 'var(--text-primary)',+ fontSize: 11, fontWeight: 500, padding: '5px 10px', borderRadius: 8,+ boxShadow: '0 4px 12px rgba(0,0,0,0.15)', border: '1px solid var(--border-faint)',+ }}>+ {voter.username}+ </div>,+ document.body+ )}+ </>)}// ── Poll Card ────────────────────────────────────────────────────────────────-function PollCard({ poll, currentUser, onVote, onClose, onDelete, t }) {- const isCreator = poll.created_by?.id === currentUser.id+ const total = totalVotes(poll)const isClosed = poll.is_closed || isExpired(poll.deadline)const remaining = timeRemaining(poll.deadline)- const total = totalVotes(poll)+ const hasVoted = (poll.options || []).some(o => (o.voters || []).some(v => String(v.user_id) === String(currentUser.id)))return (- <div- style={{- borderRadius: 10,- border: '1px solid var(--border-faint)',- padding: 12,- background: 'var(--bg-card)',- opacity: isClosed ? 0.6 : 1,- fontFamily: FONT,- }}- >- {/* Header row */}- <div- style={{- display: 'flex',- alignItems: 'flex-start',- justifyContent: 'space-between',- gap: 8,- marginBottom: 8,- }}- >+ <div style={{+ borderRadius: 14, border: '1px solid var(--border-faint)', overflow: 'hidden',+ background: 'var(--bg-card)', fontFamily: FONT,+ }}>+ {/* Header */}+ <div style={{+ padding: '10px 12px', display: 'flex', alignItems: 'flex-start', gap: 8,+ background: isClosed ? 'var(--bg-secondary)' : 'transparent',+ }}><div style={{ flex: 1, minWidth: 0 }}>- {/* Question */}- <div- style={{- fontSize: 13,- fontWeight: 600,- color: 'var(--text-primary)',- fontFamily: FONT,- lineHeight: 1.35,- wordBreak: 'break-word',- margin: 0,- }}- >+ <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1.35, wordBreak: 'break-word' }}>{poll.question}</div>-- {/* Meta line */}- <div- style={{- display: 'flex',- alignItems: 'center',- gap: 8,- marginTop: 3,- flexWrap: 'wrap',- }}- >- {/* by username */}- <span- style={{- fontSize: 10,- color: 'var(--text-faint)',- fontFamily: FONT,- }}- >- by {poll.created_by?.username || '?'}- </span>-- {/* Vote count */}- <span- style={{- fontSize: 10,- color: 'var(--text-faint)',- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 3,- }}- >- <BarChart3 size={9} />- {total} {t('collab.polls.votes')}- </span>-- {/* Multiple choice badge */}- {poll.multiple_choice && (- <span- style={{- fontSize: 9,- fontWeight: 600,- color: 'var(--accent)',- padding: '1px 6px',- borderRadius: 4,- background: 'var(--bg-tertiary)',- textTransform: 'uppercase',- letterSpacing: 0.3,- fontFamily: FONT,- }}- >- {t('collab.polls.multipleChoice')}+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4, flexWrap: 'wrap' }}>+ {isClosed && (+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', background: 'var(--bg-tertiary)', padding: '2px 7px', borderRadius: 99 }}>+ <Lock size={8} /> {t('collab.polls.closed')}</span>)}-- {/* Closed badge */}- {isClosed && (- <span- style={{- fontSize: 9,- padding: '1px 6px',- borderRadius: 4,- background: 'var(--bg-tertiary)',- color: 'var(--text-faint)',- fontWeight: 600,- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 3,- textTransform: 'uppercase',- letterSpacing: 0.3,- }}- >- <Lock size={8} />- {t('collab.polls.closed')}+ {remaining && !isClosed && (+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 9, fontWeight: 600, color: '#f59e0b', background: '#f59e0b18', padding: '2px 7px', borderRadius: 99 }}>+ <Clock size={8} /> {remaining}</span>)}-- {/* Deadline countdown */}- {!isClosed && remaining && (- <span- style={{- fontSize: 10,- color: 'var(--text-faint)',- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 3,- }}- >- <Clock size={9} />- {remaining}+ {poll.multiple_choice && (+ <span style={{ fontSize: 9, fontWeight: 600, color: 'var(--text-faint)', background: 'var(--bg-tertiary)', padding: '2px 7px', borderRadius: 99 }}>+ {t('collab.polls.multiChoice')}</span>)}+ <span style={{ fontSize: 9, color: 'var(--text-faint)' }}>+ {total} {total === 1 ? 'vote' : 'votes'}+ </span></div></div>+ {/* Actions */}+ <div style={{ display: 'flex', gap: 2, flexShrink: 0 }}>+ {!isClosed && (+ <button onClick={() => onClose(poll.id)} title={t('collab.polls.close')}+ style={{ padding: 4, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', borderRadius: 6 }}+ onMouseEnter={e => e.currentTarget.style.color = 'var(--text-primary)'}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ <Lock size={12} />+ </button>+ )}+ <button onClick={() => onDelete(poll.id)} title={t('collab.polls.delete')}+ style={{ padding: 4, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-faint)', display: 'flex', borderRadius: 6 }}+ onMouseEnter={e => e.currentTarget.style.color = '#ef4444'}+ onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>+ <Trash2 size={12} />+ </button>+ </div>+ </div>- {/* Creator actions: close / delete */}- {isCreator && (- <div style={{ display: 'flex', alignItems: 'center', gap: 2, flexShrink: 0 }}>- {!isClosed && (- <button- onClick={() => onClose(poll.id)}- title={t('collab.polls.close')}- style={{- background: 'none',- border: 'none',- cursor: 'pointer',- padding: 4,- color: 'var(--text-faint)',- fontSize: 10,- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- }}- onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--text-primary)')}- onMouseLeave={(e) => (e.currentTarget.style.color = 'var(--text-faint)')}- >- <Lock size={12} />- </button>- )}- <button- onClick={() => onDelete(poll.id)}- title={t('common.delete', 'Delete')}+ {/* Options */}+ <div style={{ padding: '4px 12px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>+ {(poll.options || []).map((opt, idx) => {+ const count = opt.voters?.length || 0+ const pct = total > 0 ? Math.round((count / total) * 100) : 0+ const myVote = (opt.voters || []).some(v => String(v.user_id) === String(currentUser.id))+ const isWinner = isClosed && count === Math.max(...(poll.options || []).map(o => o.voters?.length || 0)) && count > 0++ return (+ <button key={idx} onClick={() => !isClosed && onVote(poll.id, idx)}+ disabled={isClosed}style={{- background: 'none',- border: 'none',- cursor: 'pointer',- padding: 4,- color: 'var(--text-faint)',- fontSize: 10,- fontFamily: FONT,- display: 'flex',- alignItems: 'center',+ position: 'relative', display: 'flex', alignItems: 'center', gap: 8,+ padding: '10px 12px', borderRadius: 10, border: 'none', cursor: isClosed ? 'default' : 'pointer',+ background: 'var(--bg-secondary)', fontFamily: FONT, textAlign: 'left', width: '100%',+ overflow: 'hidden', transition: 'transform 0.1s',}}- onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--danger, #ef4444)')}- onMouseLeave={(e) => (e.currentTarget.style.color = 'var(--text-faint)')}+ onMouseEnter={e => { if (!isClosed) e.currentTarget.style.transform = 'scale(1.01)' }}+ onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>- <Trash2 size={12} />- </button>- </div>- )}- </div>+ {/* Progress bar background */}+ <div style={{+ position: 'absolute', left: 0, top: 0, bottom: 0,+ width: `${pct}%`, borderRadius: 10,+ background: myVote ? '#007AFF20' : isWinner ? '#10b98118' : 'var(--bg-tertiary)',+ transition: 'width 0.4s ease',+ }} />++ {/* Check circle */}+ <div style={{+ width: 20, height: 20, borderRadius: '50%', flexShrink: 0, position: 'relative',+ border: myVote ? '2px solid #007AFF' : '2px solid var(--border-primary)',+ background: myVote ? '#007AFF' : 'transparent',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ transition: 'all 0.2s',+ }}>+ {myVote && <Check size={11} color="#fff" strokeWidth={3} />}+ </div>- {/* Options */}- <div>- {poll.options?.map((opt, i) => (- <OptionBar- key={i}- option={opt}- index={i}- poll={poll}- currentUser={currentUser}- onVote={onVote}- isClosed={isClosed}- />- ))}+ {/* Label */}+ <span style={{+ flex: 1, fontSize: 13, fontWeight: myVote || isWinner ? 600 : 400,+ color: 'var(--text-primary)', position: 'relative', zIndex: 1,+ }}>+ {typeof opt === 'string' ? opt : opt.label || opt}+ </span>++ {/* Voter avatars */}+ {(opt.voters || []).length > 0 && (hasVoted || isClosed) && (+ <div style={{ display: 'flex', position: 'relative', zIndex: 1 }}>+ {(opt.voters || []).slice(0, 3).map((v, vi) => (+ <VoterChip key={v.user_id || vi} voter={v} offset={vi > 0} />+ ))}+ </div>+ )}++ {/* Percentage */}+ {(hasVoted || isClosed) && (+ <span style={{+ fontSize: 12, fontWeight: 700, color: myVote ? '#007AFF' : 'var(--text-muted)',+ position: 'relative', zIndex: 1, minWidth: 32, textAlign: 'right',+ }}>+ {pct}%+ </span>+ )}+ </button>+ )+ })}</div></div>)}// ── Main Component ───────────────────────────────────────────────────────────--function CollabPolls({ tripId, currentUser }) {+export default function CollabPolls({ tripId, currentUser }) {const { t } = useTranslation()const [polls, setPolls] = useState([])const [loading, setLoading] = useState(true)const [showForm, setShowForm] = useState(false)- // ── Load polls ──- const loadPolls = useCallback(async () => {- try {- const data = await collabApi.getPolls(tripId)+ useEffect(() => {+ collabApi.getPolls(tripId).then(data => {setPolls(Array.isArray(data) ? data : data.polls || [])- } catch (err) {- console.error('Failed to load polls:', err)- } finally {- setLoading(false)- }+ }).catch(() => {}).finally(() => setLoading(false))}, [tripId])- useEffect(() => {- loadPolls()- }, [loadPolls])-- // ── WebSocket ──+ // WebSocketuseEffect(() => {const handler = (msg) => {- if (!msg || !msg.type) return-+ if (!msg?.type) returnif (msg.type === 'collab:poll:created' && msg.poll) {- setPolls((prev) => {- if (prev.some((p) => p.id === msg.poll.id)) return prev- return [msg.poll, ...prev]- })+ setPolls(prev => prev.some(p => p.id === msg.poll.id) ? prev : [msg.poll, ...prev])}-if (msg.type === 'collab:poll:voted' && msg.poll) {- setPolls((prev) =>- prev.map((p) => (p.id === msg.poll.id ? msg.poll : p))- )+ setPolls(prev => prev.map(p => p.id === msg.poll.id ? msg.poll : p))}-if (msg.type === 'collab:poll:closed' && msg.poll) {- setPolls((prev) =>- prev.map((p) => (p.id === msg.poll.id ? { ...p, ...msg.poll, is_closed: true } : p))- )+ setPolls(prev => prev.map(p => p.id === msg.poll.id ? { ...p, ...msg.poll, is_closed: true } : p))}-if (msg.type === 'collab:poll:deleted') {- const deletedId = msg.pollId || msg.poll?.id || msg.id- if (deletedId) {- setPolls((prev) => prev.filter((p) => p.id !== deletedId))- }+ const id = msg.pollId || msg.poll?.id+ if (id) setPolls(prev => prev.filter(p => p.id !== id))}}-addListener(handler)return () => removeListener(handler)}, [])- // ── Actions ──- const handleCreate = useCallback(- async (data) => {- const result = await collabApi.createPoll(tripId, data)- const created = result.poll || result- setPolls((prev) => {- if (prev.some((p) => p.id === created.id)) return prev- return [created, ...prev]- })- setShowForm(false)- },- [tripId]- )+ const handleCreate = useCallback(async (data) => {+ const result = await collabApi.createPoll(tripId, data)+ const created = result.poll || result+ setPolls(prev => prev.some(p => p.id === created.id) ? prev : [created, ...prev])+ setShowForm(false)+ }, [tripId])- const handleVote = useCallback(- async (pollId, optionIndex) => {- try {- const result = await collabApi.votePoll(tripId, pollId, optionIndex)- const updated = result.poll || result- setPolls((prev) =>- prev.map((p) => (p.id === updated.id ? updated : p))- )- } catch (err) {- console.error('Vote failed:', err)- }- },- [tripId]- )+ const handleVote = useCallback(async (pollId, optionIndex) => {+ try {+ const result = await collabApi.votePoll(tripId, pollId, optionIndex)+ const updated = result.poll || result+ setPolls(prev => prev.map(p => p.id === updated.id ? updated : p))+ } catch {}+ }, [tripId])- const handleClose = useCallback(- async (pollId) => {- try {- await collabApi.closePoll(tripId, pollId)- setPolls((prev) =>- prev.map((p) => (p.id === pollId ? { ...p, is_closed: true } : p))- )- } catch (err) {- console.error('Close poll failed:', err)- }- },- [tripId]- )+ const handleClose = useCallback(async (pollId) => {+ try {+ await collabApi.closePoll(tripId, pollId)+ setPolls(prev => prev.map(p => p.id === pollId ? { ...p, is_closed: true } : p))+ } catch {}+ }, [tripId])- const handleDelete = useCallback(- async (pollId) => {- try {- await collabApi.deletePoll(tripId, pollId)- setPolls((prev) => prev.filter((p) => p.id !== pollId))- } catch (err) {- console.error('Delete poll failed:', err)- }- },- [tripId]- )+ const handleDelete = useCallback(async (pollId) => {+ try {+ await collabApi.deletePoll(tripId, pollId)+ setPolls(prev => prev.filter(p => p.id !== pollId))+ } catch {}+ }, [tripId])- // ── Separate active / closed ──- const activePolls = polls.filter(- (p) => !p.is_closed && !isExpired(p.deadline)- )- const closedPolls = polls.filter(- (p) => p.is_closed || isExpired(p.deadline)- )+ const activePolls = polls.filter(p => !p.is_closed && !isExpired(p.deadline))+ const closedPolls = polls.filter(p => p.is_closed || isExpired(p.deadline))- // ── Deadline countdown ticker ──+ // Deadline tickerconst [, setTick] = useState(0)useEffect(() => {- const hasDeadlines = polls.some((p) => p.deadline && !p.is_closed)- if (!hasDeadlines) return- const iv = setInterval(() => setTick((t) => t + 1), 30000)+ if (!polls.some(p => p.deadline && !p.is_closed)) return+ const iv = setInterval(() => setTick(t => t + 1), 30000)return () => clearInterval(iv)}, [polls])- // ── Render ──+ if (loading) {+ return (+ <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FONT }}>+ <div style={{ width: 20, height: 20, border: '2px solid var(--border-primary)', borderTopColor: 'var(--text-primary)', borderRadius: '50%', animation: 'collab-poll-spin 0.7s linear infinite' }} />+ <style>{`@keyframes collab-poll-spin { to { transform: rotate(360deg) } }`}</style>+ </div>+ )+ }+return (- <div- style={{- height: '100%',- display: 'flex',- flexDirection: 'column',- fontFamily: FONT,- }}- >- {/* Header — fixed */}- <div- style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- padding: '12px 16px',- borderBottom: '1px solid var(--border-faint)',- flexShrink: 0,- }}- >- <h3- style={{- margin: 0,- fontSize: 14,- fontWeight: 700,- color: 'var(--text-primary)',- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 6,- }}- >- <BarChart3 size={14} style={{ color: 'var(--accent)' }} />+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column', fontFamily: FONT }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px', flexShrink: 0 }}>+ <h3 style={{ margin: 0, fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 7, letterSpacing: 0.3, textTransform: 'uppercase' }}>+ <BarChart3 size={14} color="var(--text-faint)" />{t('collab.polls.title')}</h3>- {!showForm && (- <button- onClick={() => setShowForm(true)}- style={{- background: 'var(--accent)',- border: 'none',- borderRadius: 99,- padding: '4px 12px',- fontSize: 11,- fontWeight: 600,- color: '#fff',- cursor: 'pointer',- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 3,- }}- onMouseEnter={(e) => (e.currentTarget.style.opacity = '0.85')}- onMouseLeave={(e) => (e.currentTarget.style.opacity = '1')}- >- <Plus size={11} />- {t('collab.polls.new')}- </button>- )}+ <button onClick={() => setShowForm(true)} style={{+ display: 'inline-flex', alignItems: 'center', gap: 4, borderRadius: 99, padding: '6px 12px',+ background: 'var(--accent)', color: 'var(--accent-text)', fontSize: 11, fontWeight: 600,+ fontFamily: FONT, border: 'none', cursor: 'pointer',+ }}>+ <Plus size={12} /> {t('collab.polls.new')}+ </button></div>- {/* Content — scrollable */}- <div- style={{- flex: 1,- overflowY: 'auto',- padding: 12,- }}- >- {/* Create form */}- {showForm && (- <CreatePollForm- onSubmit={handleCreate}- onCancel={() => setShowForm(false)}- t={t}- />- )}-- {/* Loading */}- {loading && (- <div- style={{- textAlign: 'center',- padding: '32px 0',- color: 'var(--text-faint)',- fontSize: 12,- fontFamily: FONT,- }}- >- ...- </div>- )}-- {/* Empty state */}- {!loading && polls.length === 0 && !showForm && (- <div- style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- padding: '40px 16px',- textAlign: 'center',- }}- >- <BarChart3- size={36}- style={{- color: 'var(--text-faint)',- marginBottom: 10,- }}- />- <div- style={{- fontSize: 14,- fontWeight: 600,- color: 'var(--text-primary)',- fontFamily: FONT,- marginBottom: 4,- }}- >- {t('collab.polls.empty')}- </div>- <div- style={{- fontSize: 12,- color: 'var(--text-faint)',- fontFamily: FONT,- }}- >- {t('collab.polls.emptyDesc', 'Create a poll to get started')}- </div>+ {/* Content */}+ <div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '0 12px 12px' }}>+ {polls.length === 0 ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '48px 20px', textAlign: 'center', height: '100%' }}>+ <BarChart3 size={36} color="var(--text-faint)" strokeWidth={1.3} style={{ marginBottom: 12 }} />+ <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>{t('collab.polls.empty')}</div>+ <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{t('collab.polls.emptyHint')}</div></div>- )}-- {/* Active polls */}- {!loading && (- <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>- {activePolls.map((poll) => (- <PollCard- key={poll.id}- poll={poll}- currentUser={currentUser}- onVote={handleVote}- onClose={handleClose}- onDelete={handleDelete}- t={t}- />+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>+ {activePolls.length > 0 && activePolls.map(poll => (+ <PollCard key={poll.id} poll={poll} currentUser={currentUser} onVote={handleVote} onClose={handleClose} onDelete={handleDelete} t={t} />))}- </div>- )}-- {/* Closed polls divider + section */}- {!loading && closedPolls.length > 0 && (- <>- {activePolls.length > 0 && (- <div- style={{- display: 'flex',- alignItems: 'center',- gap: 8,- margin: '12px 0 8px',- }}- >- <div- style={{- flex: 1,- height: 1,- background: 'var(--border-faint)',- }}- />- <span- style={{- fontSize: 9,- fontWeight: 600,- color: 'var(--text-faint)',- textTransform: 'uppercase',- letterSpacing: 0.5,- fontFamily: FONT,- display: 'flex',- alignItems: 'center',- gap: 4,- whiteSpace: 'nowrap',- }}- >- <Lock size={9} />- {t('collab.polls.closed')}- </span>- <div- style={{- flex: 1,- height: 1,- background: 'var(--border-faint)',- }}- />- </div>+ {closedPolls.length > 0 && (+ <>+ {activePolls.length > 0 && (+ <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.3, padding: '8px 0 2px' }}>+ {t('collab.polls.closedSection') || 'Closed'}+ </div>+ )}+ {closedPolls.map(poll => (+ <PollCard key={poll.id} poll={poll} currentUser={currentUser} onVote={handleVote} onClose={handleClose} onDelete={handleDelete} t={t} />+ ))}+ </>)}- <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>- {closedPolls.map((poll) => (- <PollCard- key={poll.id}- poll={poll}- currentUser={currentUser}- onVote={handleVote}- onClose={handleClose}- onDelete={handleDelete}- t={t}- />- ))}- </div>- </>+ </div>)}</div>++ {/* Create Modal */}+ {showForm && <CreatePollModal onClose={() => setShowForm(false)} onCreate={handleCreate} t={t} />}</div>)}--export default CollabPollsdiff --git a/client/src/components/Collab/WhatsNextWidget.jsx b/client/src/components/Collab/WhatsNextWidget.jsxnew file mode 100644index 000000000..411483de9--- /dev/null+++ b/client/src/components/Collab/WhatsNextWidget.jsx@@ -0,0 +1,189 @@+import React, { useMemo } from 'react'+import { useTripStore } from '../../store/tripStore'+import { useSettingsStore } from '../../store/settingsStore'+import { useTranslation } from '../../i18n'+import { MapPin, Clock, Calendar, Users, Sparkles } from 'lucide-react'++function formatTime(timeStr, is12h) {+ if (!timeStr) return ''+ const [h, m] = timeStr.split(':').map(Number)+ if (is12h) {+ const period = h >= 12 ? 'PM' : 'AM'+ const h12 = h === 0 ? 12 : h > 12 ? h - 12 : h+ return `${h12}:${String(m).padStart(2, '0')} ${period}`+ }+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`+}++function formatDayLabel(date, t, locale) {+ const d = new Date(date + 'T00:00:00')+ const now = new Date()+ const tomorrow = new Date(); tomorrow.setDate(now.getDate() + 1)++ if (d.toDateString() === now.toDateString()) return t('collab.whatsNext.today') || 'Today'+ if (d.toDateString() === tomorrow.toDateString()) return t('collab.whatsNext.tomorrow') || 'Tomorrow'++ return d.toLocaleDateString(locale || undefined, { weekday: 'short', day: 'numeric', month: 'short' })+}++export default function WhatsNextWidget({ tripMembers = [] }) {+ const { days, assignments } = useTripStore()+ const { t, locale } = useTranslation()+ const is12h = useSettingsStore(s => s.settings.time_format) === '12h'++ const upcoming = useMemo(() => {+ const now = new Date()+ const nowDate = now.toISOString().split('T')[0]+ const nowTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`+ const items = []++ for (const day of (days || [])) {+ if (!day.date) continue+ const dayAssignments = assignments[String(day.id)] || []+ for (const a of dayAssignments) {+ if (!a.place) continue+ // Include: today (future times) + all future days+ const isFutureDay = day.date > nowDate+ const isTodayFuture = day.date === nowDate && (!a.place.place_time || a.place.place_time >= nowTime)+ if (isFutureDay || isTodayFuture) {+ items.push({+ id: a.id,+ name: a.place.name,+ time: a.place.place_time,+ endTime: a.place.end_time,+ date: day.date,+ dayTitle: day.title,+ category: a.place.category,+ participants: (a.participants && a.participants.length > 0)+ ? a.participants+ : tripMembers.map(m => ({ user_id: m.id, username: m.username, avatar: m.avatar })),+ address: a.place.address,+ })+ }+ }+ }++ items.sort((a, b) => {+ const da = a.date + (a.time || '99:99')+ const db = b.date + (b.time || '99:99')+ return da.localeCompare(db)+ })++ return items.slice(0, 8)+ }, [days, assignments, tripMembers])++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>+ {/* Header */}+ <div style={{+ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 7, flexShrink: 0,+ }}>+ <Sparkles size={14} color="var(--text-faint)" />+ <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', letterSpacing: 0.3, textTransform: 'uppercase' }}>+ {t('collab.whatsNext.title') || "What's Next"}+ </span>+ </div>++ {/* List */}+ <div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '8px 10px' }}>+ {upcoming.length === 0 ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', padding: '48px 20px', textAlign: 'center' }}>+ <Calendar size={36} color="var(--text-faint)" strokeWidth={1.3} style={{ marginBottom: 12 }} />+ <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>{t('collab.whatsNext.empty')}</div>+ <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{t('collab.whatsNext.emptyHint')}</div>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>+ {upcoming.map((item, idx) => {+ const prevItem = upcoming[idx - 1]+ const showDayHeader = !prevItem || prevItem.date !== item.date++ return (+ <React.Fragment key={item.id}>+ {showDayHeader && (+ <div style={{+ fontSize: 10, fontWeight: 500, color: 'var(--text-faint)',+ textTransform: 'uppercase', letterSpacing: 0.5,+ padding: idx === 0 ? '0 4px 4px' : '8px 4px 4px',+ }}>+ {formatDayLabel(item.date, t, locale)}+ {item.dayTitle ? ` — ${item.dayTitle}` : ''}+ </div>+ )}++ <div style={{+ display: 'flex', gap: 10, padding: '8px 10px', borderRadius: 10,+ background: 'var(--bg-secondary)', transition: 'background 0.1s',+ }}+ onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}+ onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-secondary)'}+ >+ {/* Time column */}+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minWidth: 44, flexShrink: 0 }}>+ <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-primary)', whiteSpace: 'nowrap', lineHeight: 1 }}>+ {item.time ? formatTime(item.time, is12h) : 'TBD'}+ </span>+ {item.endTime && (+ <>+ <span style={{ fontSize: 7, color: 'var(--text-faint)', fontWeight: 600, letterSpacing: 0.3, margin: '2px 0', textTransform: 'uppercase' }}>+ {t('collab.whatsNext.until') || 'bis'}+ </span>+ <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-primary)', whiteSpace: 'nowrap', lineHeight: 1 }}>+ {formatTime(item.endTime, is12h)}+ </span>+ </>+ )}+ </div>++ {/* Divider */}+ <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--border-faint)', flexShrink: 0, margin: '2px 0' }} />++ {/* Details */}+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-primary)', lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {item.name}+ </div>+ {item.address && (+ <div style={{ display: 'flex', alignItems: 'center', gap: 3, marginTop: 2 }}>+ <MapPin size={9} color="var(--text-faint)" style={{ flexShrink: 0 }} />+ <span style={{ fontSize: 10, color: 'var(--text-faint)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {item.address}+ </span>+ </div>+ )}++ {/* Participants */}+ {item.participants.length > 0 && (+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 5 }}>+ {item.participants.map(p => (+ <div key={p.user_id} style={{+ display: 'flex', alignItems: 'center', gap: 4, padding: '2px 8px 2px 3px',+ borderRadius: 99, background: 'var(--bg-tertiary)', border: '1px solid var(--border-faint)',+ }}>+ <div style={{+ width: 16, height: 16, borderRadius: '50%', background: 'var(--bg-secondary)',+ display: 'flex', alignItems: 'center', justifyContent: 'center',+ fontSize: 7, fontWeight: 700, color: 'var(--text-muted)',+ overflow: 'hidden', flexShrink: 0,+ }}>+ {p.avatar+ ? <img src={`/uploads/avatars/${p.avatar}`} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />+ : p.username?.[0]?.toUpperCase()+ }+ </div>+ <span style={{ fontSize: 10, fontWeight: 500, color: 'var(--text-muted)' }}>{p.username}</span>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ </React.Fragment>+ )+ })}+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/client/src/components/Files/FileManager.jsx b/client/src/components/Files/FileManager.jsxindex 2c5ef26b0..e8c28d047 100644--- a/client/src/components/Files/FileManager.jsx+++ b/client/src/components/Files/FileManager.jsx@@ -1,7 +1,7 @@import React, { useState, useCallback } from 'react'import ReactDOM from 'react-dom'import { useDropzone } from 'react-dropzone'-import { Upload, Trash2, ExternalLink, X, FileText, FileImage, File, MapPin, Ticket } from 'lucide-react'+import { Upload, Trash2, ExternalLink, X, FileText, FileImage, File, MapPin, Ticket, StickyNote } from 'lucide-react'import { useToast } from '../shared/Toast'import { useTranslation } from '../../i18n'@@ -128,6 +128,7 @@ export default function FileManager({ files = [], onUpload, onDelete, onUpdate,if (filterType === 'pdf') return f.mime_type === 'application/pdf'if (filterType === 'image') return isImage(f.mime_type)if (filterType === 'doc') return (f.mime_type || '').includes('word') || (f.mime_type || '').includes('excel') || (f.mime_type || '').includes('text')+ if (filterType === 'collab') return !!f.note_idreturn true})@@ -243,6 +244,7 @@ export default function FileManager({ files = [], onUpload, onDelete, onUpdate,{ id: 'pdf', label: t('files.filterPdf') },{ id: 'image', label: t('files.filterImages') },{ id: 'doc', label: t('files.filterDocs') },+ ...(files.some(f => f.note_id) ? [{ id: 'collab', label: t('files.filterCollab') || 'Collab' }] : []),].map(tab => (<button key={tab.id} onClick={() => setFilterType(tab.id)} style={{padding: '4px 12px', borderRadius: 99, border: 'none', cursor: 'pointer', fontSize: 12,@@ -273,7 +275,7 @@ export default function FileManager({ files = [], onUpload, onDelete, onUpdate,const linkedReservation = file.reservation_id? (reservations?.find(r => r.id === file.reservation_id) || { title: file.reservation_title }): null- const fileUrl = file.url || `/uploads/files/${file.filename}`+ const fileUrl = file.url || (file.filename?.startsWith('files/') ? `/uploads/${file.filename}` : `/uploads/files/${file.filename}`)return (<div key={file.id} style={{@@ -296,7 +298,15 @@ export default function FileManager({ files = [], onUpload, onDelete, onUpdate,>{isImage(file.mime_type)? <img src={fileUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />- : <FileIcon size={16} style={{ color: 'var(--text-muted)' }} />+ : (() => {+ const ext = (file.original_name || '').split('.').pop()?.toUpperCase() || '?'+ const isPdf = file.mime_type === 'application/pdf'+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%', height: '100%', background: isPdf ? '#ef44441a' : 'var(--bg-tertiary)' }}>+ <span style={{ fontSize: 9, fontWeight: 700, color: isPdf ? '#ef4444' : 'var(--text-muted)', letterSpacing: 0.3 }}>{ext}</span>+ </div>+ )+ })()}</div>@@ -325,6 +335,12 @@ export default function FileManager({ files = [], onUpload, onDelete, onUpdate,label={`${t('files.sourceBooking')} · ${linkedReservation.title || t('files.sourceBooking')}`}/>)}+ {file.note_id && (+ <SourceBadge+ icon={StickyNote}+ label={t('files.sourceCollab') || 'Collab Notes'}+ />+ )}</div>{file.description && !linkedReservation && (diff --git a/client/src/components/Map/MapView.jsx b/client/src/components/Map/MapView.jsxindex 7114ae177..4424c166f 100644--- a/client/src/components/Map/MapView.jsx+++ b/client/src/components/Map/MapView.jsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState, useMemo } from 'react'+import ReactDOM from 'react-dom'import { MapContainer, TileLayer, Marker, Tooltip, Polyline, useMap } from 'react-leaflet'import MarkerClusterGroup from 'react-leaflet-cluster'import L from 'leaflet'@@ -158,6 +159,50 @@ function MapClickHandler({ onClick }) {return null}+// ── Route travel time label ──+function RouteLabel({ midpoint, walkingText, drivingText }) {+ const map = useMap()+ const [visible, setVisible] = useState(map ? map.getZoom() >= 16 : false)++ useEffect(() => {+ if (!map) return+ const check = () => setVisible(map.getZoom() >= 16)+ check()+ map.on('zoomend', check)+ return () => map.off('zoomend', check)+ }, [map])++ if (!visible || !midpoint) return null++ const icon = L.divIcon({+ className: 'route-info-pill',+ html: `<div style="+ display:flex;align-items:center;gap:5px;+ background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);+ color:#fff;border-radius:99px;padding:3px 9px;+ font-size:9px;font-weight:600;white-space:nowrap;+ font-family:-apple-system,BlinkMacSystemFont,system-ui,sans-serif;+ box-shadow:0 2px 12px rgba(0,0,0,0.3);+ pointer-events:none;+ position:relative;left:-50%;top:-50%;+ ">+ <span style="display:flex;align-items:center;gap:2px">+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="13" cy="4" r="2"/><path d="M7 21l3-7"/><path d="M10 14l5-5"/><path d="M15 9l-4 7"/><path d="M18 18l-3-7"/></svg>+ ${walkingText}+ </span>+ <span style="opacity:0.3">|</span>+ <span style="display:flex;align-items:center;gap:2px">+ <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9L18 10l-2-4H7L5 10l-2.5 1.1C1.7 11.3 1 12.1 1 13v3c0 .6.4 1 1 1h2"/><circle cx="7" cy="17" r="2"/><circle cx="17" cy="17" r="2"/></svg>+ ${drivingText}+ </span>+ </div>`,+ iconSize: [0, 0],+ iconAnchor: [0, 0],+ })++ return <Marker position={midpoint} icon={icon} interactive={false} zIndexOffset={2000} />+}+// Module-level photo cache shared with PlaceAvatarconst mapPhotoCache = new Map()@@ -165,6 +210,7 @@ export function MapView({places = [],dayPlaces = [],route = null,+ routeSegments = [],selectedPlaceId = null,onMarkerClick,onMapClick,@@ -297,13 +343,18 @@ export function MapView({</MarkerClusterGroup>{route && route.length > 1 && (- <Polyline- positions={route}- color="#111827"- weight={3}- opacity={0.9}- dashArray="6, 5"- />+ <>+ <Polyline+ positions={route}+ color="#111827"+ weight={3}+ opacity={0.9}+ dashArray="6, 5"+ />+ {routeSegments.map((seg, i) => (+ <RouteLabel key={i} midpoint={seg.mid} from={seg.from} to={seg.to} walkingText={seg.walkingText} drivingText={seg.drivingText} />+ ))}+ </>)}</MapContainer>)diff --git a/client/src/components/Map/RouteCalculator.js b/client/src/components/Map/RouteCalculator.jsindex c1855a9cc..b0b543820 100644--- a/client/src/components/Map/RouteCalculator.js+++ b/client/src/components/Map/RouteCalculator.js@@ -41,12 +41,17 @@ export async function calculateRoute(waypoints, profile = 'driving') {duration = route.duration // driving: use OSRM value}+ const walkingDuration = distance / (5000 / 3600) // 5 km/h+ const drivingDuration = route.duration // OSRM driving value+return {coordinates,distance,duration,distanceText: formatDistance(distance),durationText: formatDuration(duration),+ walkingText: formatDuration(walkingDuration),+ drivingText: formatDuration(drivingDuration),}}diff --git a/client/src/components/Planner/DayPlanSidebar.jsx b/client/src/components/Planner/DayPlanSidebar.jsxindex 2ba643bf8..95fca0703 100644--- a/client/src/components/Planner/DayPlanSidebar.jsx+++ b/client/src/components/Planner/DayPlanSidebar.jsx@@ -92,7 +92,13 @@ export default function DayPlanSidebar({const dayNotes = tripStore.dayNotes || {}- const [expandedDays, setExpandedDays] = useState(() => new Set(days.map(d => d.id)))+ const [expandedDays, setExpandedDays] = useState(() => {+ try {+ const saved = sessionStorage.getItem(`day-expanded-${tripId}`)+ if (saved) return new Set(JSON.parse(saved))+ } catch {}+ return new Set(days.map(d => d.id))+ })const [editingDayId, setEditingDayId] = useState(null)const [editTitle, setEditTitle] = useState('')const [isCalculating, setIsCalculating] = useState(false)@@ -128,9 +134,20 @@ export default function DayPlanSidebar({return { placeId, assignmentId: '', noteId: '', fromDayId: 0 }}+ // Only auto-expand genuinely new days (not on initial load from storage)+ const prevDayCount = React.useRef(days.length)useEffect(() => {- setExpandedDays(prev => new Set([...prev, ...days.map(d => d.id)]))- }, [days.length])+ if (days.length > prevDayCount.current) {+ // New days added — expand only those+ setExpandedDays(prev => {+ const n = new Set(prev)+ days.forEach(d => { if (!prev.has(d.id)) n.add(d.id) })+ try { sessionStorage.setItem(`day-expanded-${tripId}`, JSON.stringify([...n])) } catch {}+ return n+ })+ }+ prevDayCount.current = days.length+ }, [days.length, tripId])useEffect(() => {if (editingDayId && inputRef.current) inputRef.current.focus()@@ -154,6 +171,7 @@ export default function DayPlanSidebar({setExpandedDays(prev => {const n = new Set(prev)n.has(dayId) ? n.delete(dayId) : n.add(dayId)+ try { sessionStorage.setItem(`day-expanded-${tripId}`, JSON.stringify([...n])) } catch {}return n})}diff --git a/client/src/i18n/translations/de.js b/client/src/i18n/translations/de.jsindex 65a365103..80eb61b31 100644--- a/client/src/i18n/translations/de.js+++ b/client/src/i18n/translations/de.js@@ -127,6 +127,9 @@ const de = {'settings.language': 'Sprache','settings.temperature': 'Temperatureinheit','settings.timeFormat': 'Zeitformat',+ 'settings.routeCalculation': 'Routenberechnung',+ 'settings.on': 'An',+ 'settings.off': 'Aus','settings.account': 'Konto','settings.username': 'Benutzername','settings.email': 'E-Mail',@@ -660,6 +663,8 @@ const de = {'files.filterPdf': 'PDFs','files.filterImages': 'Bilder','files.filterDocs': 'Dokumente',+ 'files.filterCollab': 'Collab Notizen',+ 'files.sourceCollab': 'Aus Collab Notizen','files.empty': 'Keine Dateien vorhanden','files.emptyHint': 'Lade Dateien hoch, um sie mit deiner Reise zu verknüpfen','files.openTab': 'In neuem Tab öffnen',@@ -925,6 +930,7 @@ const de = {'day.hourlyForecast': 'Stündliche Vorhersage','day.climateHint': 'Historische Durchschnittswerte — echte Vorhersage verfügbar innerhalb von 16 Tagen vor diesem Datum.','day.noWeather': 'Keine Wetterdaten verfügbar. Füge einen Ort mit Koordinaten hinzu.',+ 'day.overview': 'Tagesübersicht','day.accommodation': 'Unterkunft','day.addAccommodation': 'Unterkunft hinzufügen','day.hotelDayRange': 'Auf Tage anwenden',@@ -940,10 +946,19 @@ const de = {'collab.tabs.chat': 'Chat','collab.tabs.notes': 'Notizen','collab.tabs.polls': 'Umfragen',+ 'collab.whatsNext.title': 'Nächste',+ 'collab.whatsNext.today': 'Heute',+ 'collab.whatsNext.tomorrow': 'Morgen',+ 'collab.whatsNext.empty': 'Keine anstehenden Aktivitäten',+ 'collab.whatsNext.until': 'bis',+ 'collab.whatsNext.emptyHint': 'Aktivitäten mit Uhrzeit erscheinen hier','collab.chat.send': 'Senden','collab.chat.placeholder': 'Nachricht eingeben...','collab.chat.empty': 'Starte die Unterhaltung','collab.chat.emptyHint': 'Nachrichten werden mit allen Reiseteilnehmern geteilt',+ 'collab.chat.today': 'Heute',+ 'collab.chat.yesterday': 'Gestern',+ 'collab.chat.deletedMessage': 'hat eine Nachricht gelöscht','collab.chat.loadMore': 'Ältere Nachrichten laden','collab.chat.justNow': 'gerade eben','collab.chat.minutesAgo': 'vor {n} Min.',@@ -958,6 +973,23 @@ const de = {'collab.notes.contentPlaceholder': 'Schreibe etwas...','collab.notes.categoryPlaceholder': 'Kategorie','collab.notes.newCategory': 'Neue Kategorie...',+ 'collab.notes.category': 'Kategorie',+ 'collab.notes.noCategory': 'Keine Kategorie',+ 'collab.notes.color': 'Farbe',+ 'collab.notes.save': 'Speichern',+ 'collab.notes.cancel': 'Abbrechen',+ 'collab.notes.edit': 'Bearbeiten',+ 'collab.notes.delete': 'Löschen',+ 'collab.notes.pin': 'Anheften',+ 'collab.notes.unpin': 'Loslösen',+ 'collab.notes.daysAgo': 'vor {n} T.',+ 'collab.notes.categorySettings': 'Kategorien verwalten',+ 'collab.notes.create': 'Erstellen',+ 'collab.notes.website': 'Website',+ 'collab.notes.websitePlaceholder': 'https://...',+ 'collab.notes.attachFiles': 'Dateien anhängen',+ 'collab.notes.noCategoriesYet': 'Noch keine Kategorien',+ 'collab.notes.emptyDesc': 'Erstelle eine Notiz um loszulegen','collab.polls.title': 'Umfragen','collab.polls.new': 'Neue Umfrage','collab.polls.empty': 'Noch keine Umfragen',@@ -972,7 +1004,12 @@ const de = {'collab.polls.votes': '{n} Stimmen','collab.polls.vote': '{n} Stimme','collab.polls.multipleChoice': 'Mehrfachauswahl',+ 'collab.polls.multiChoice': 'Mehrfachauswahl','collab.polls.deadline': 'Frist',+ 'collab.polls.option': 'Option',+ 'collab.polls.options': 'Optionen',+ 'collab.polls.delete': 'Löschen',+ 'collab.polls.closedSection': 'Geschlossen',}export default dediff --git a/client/src/i18n/translations/en.js b/client/src/i18n/translations/en.jsindex a5df0f0fe..b3092e466 100644--- a/client/src/i18n/translations/en.js+++ b/client/src/i18n/translations/en.js@@ -127,6 +127,9 @@ const en = {'settings.language': 'Language','settings.temperature': 'Temperature Unit','settings.timeFormat': 'Time Format',+ 'settings.routeCalculation': 'Route Calculation',+ 'settings.on': 'On',+ 'settings.off': 'Off','settings.account': 'Account','settings.username': 'Username','settings.email': 'Email',@@ -660,6 +663,8 @@ const en = {'files.filterPdf': 'PDFs','files.filterImages': 'Images','files.filterDocs': 'Documents',+ 'files.filterCollab': 'Collab Notes',+ 'files.sourceCollab': 'From Collab Notes','files.empty': 'No files yet','files.emptyHint': 'Upload files to attach them to your trip','files.openTab': 'Open in new tab',@@ -925,6 +930,7 @@ const en = {'day.hourlyForecast': 'Hourly Forecast','day.climateHint': 'Historical averages — real forecast available within 16 days of this date.','day.noWeather': 'No weather data available. Add a place with coordinates.',+ 'day.overview': 'Daily Overview','day.accommodation': 'Accommodation','day.addAccommodation': 'Add accommodation','day.hotelDayRange': 'Apply to days',@@ -940,10 +946,19 @@ const en = {'collab.tabs.chat': 'Chat','collab.tabs.notes': 'Notes','collab.tabs.polls': 'Polls',+ 'collab.whatsNext.title': "What's Next",+ 'collab.whatsNext.today': 'Today',+ 'collab.whatsNext.tomorrow': 'Tomorrow',+ 'collab.whatsNext.empty': 'No upcoming activities',+ 'collab.whatsNext.until': 'to',+ 'collab.whatsNext.emptyHint': 'Activities with times will appear here','collab.chat.send': 'Send','collab.chat.placeholder': 'Type a message...','collab.chat.empty': 'Start the conversation','collab.chat.emptyHint': 'Messages are shared with all trip members',+ 'collab.chat.today': 'Today',+ 'collab.chat.yesterday': 'Yesterday',+ 'collab.chat.deletedMessage': 'deleted a message','collab.chat.loadMore': 'Load older messages','collab.chat.justNow': 'just now','collab.chat.minutesAgo': '{n}m ago',@@ -958,6 +973,23 @@ const en = {'collab.notes.contentPlaceholder': 'Write something...','collab.notes.categoryPlaceholder': 'Category','collab.notes.newCategory': 'New category...',+ 'collab.notes.category': 'Category',+ 'collab.notes.noCategory': 'No category',+ 'collab.notes.color': 'Color',+ 'collab.notes.save': 'Save',+ 'collab.notes.cancel': 'Cancel',+ 'collab.notes.edit': 'Edit',+ 'collab.notes.delete': 'Delete',+ 'collab.notes.pin': 'Pin',+ 'collab.notes.unpin': 'Unpin',+ 'collab.notes.daysAgo': '{n}d ago',+ 'collab.notes.categorySettings': 'Manage Categories',+ 'collab.notes.create': 'Create',+ 'collab.notes.website': 'Website',+ 'collab.notes.websitePlaceholder': 'https://...',+ 'collab.notes.attachFiles': 'Attach files',+ 'collab.notes.noCategoriesYet': 'No categories yet',+ 'collab.notes.emptyDesc': 'Create a note to get started','collab.polls.title': 'Polls','collab.polls.new': 'New Poll','collab.polls.empty': 'No polls yet',@@ -972,7 +1004,12 @@ const en = {'collab.polls.votes': '{n} votes','collab.polls.vote': '{n} vote','collab.polls.multipleChoice': 'Multiple choice',+ 'collab.polls.multiChoice': 'Multiple choice','collab.polls.deadline': 'Deadline',+ 'collab.polls.option': 'Option',+ 'collab.polls.options': 'Options',+ 'collab.polls.delete': 'Delete',+ 'collab.polls.closedSection': 'Closed',}export default endiff --git a/client/src/index.css b/client/src/index.cssindex e01393f7f..f45c88efc 100644--- a/client/src/index.css+++ b/client/src/index.css@@ -290,6 +290,11 @@ body {width: 6px;height: 6px;}+::-webkit-scrollbar-button {+ display: none;+ height: 0;+ width: 0;+}::-webkit-scrollbar-track {background: var(--scrollbar-track);@@ -305,6 +310,11 @@ body {background: var(--scrollbar-hover);}+.route-info-pill { background: none !important; border: none !important; box-shadow: none !important; width: auto !important; height: auto !important; margin: 0 !important; }+.chat-scroll { overflow-y: auto !important; scrollbar-width: none; -webkit-overflow-scrolling: touch; }+.chat-scroll::-webkit-scrollbar { width: 0; background: transparent; }++/* Einheitliche Formular-Inputs */.form-input {width: 100%;diff --git a/client/src/pages/SettingsPage.jsx b/client/src/pages/SettingsPage.jsxindex 2660d26ff..3eeed2d9e 100644--- a/client/src/pages/SettingsPage.jsx+++ b/client/src/pages/SettingsPage.jsx@@ -330,6 +330,35 @@ export default function SettingsPage() {))}</div></div>+ {/* Route Calculation */}+ <div>+ <label className="block text-sm font-medium mb-2" style={{ color: 'var(--text-secondary)' }}>{t('settings.routeCalculation')}</label>+ <div className="flex gap-3">+ {[+ { value: true, label: t('settings.on') || 'On' },+ { value: false, label: t('settings.off') || 'Off' },+ ].map(opt => (+ <button+ key={String(opt.value)}+ onClick={async () => {+ try { await updateSetting('route_calculation', opt.value) }+ catch (e) { toast.error(e.message) }+ }}+ style={{+ display: 'flex', alignItems: 'center', gap: 8,+ padding: '10px 20px', borderRadius: 10, cursor: 'pointer',+ fontFamily: 'inherit', fontSize: 14, fontWeight: 500,+ border: (settings.route_calculation !== false) === opt.value ? '2px solid var(--text-primary)' : '2px solid var(--border-primary)',+ background: (settings.route_calculation !== false) === opt.value ? 'var(--bg-hover)' : 'var(--bg-card)',+ color: 'var(--text-primary)',+ transition: 'all 0.15s',+ }}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div></Section>{/* Account */}diff --git a/client/src/pages/TripPlannerPage.jsx b/client/src/pages/TripPlannerPage.jsxindex 1fc67fd74..ae736f512 100644--- a/client/src/pages/TripPlannerPage.jsx+++ b/client/src/pages/TripPlannerPage.jsx@@ -23,6 +23,7 @@ import { Map, X, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpenimport { useTranslation } from '../i18n'import { joinTrip, leaveTrip, addListener, removeListener } from '../api/websocket'import { addonsApi, accommodationsApi, authApi, tripsApi, assignmentsApi } from '../api/client'+import { calculateRoute } from '../components/Map/RouteCalculator'const MIN_SIDEBAR = 200const MAX_SIDEBAR = 520@@ -65,10 +66,14 @@ export default function TripPlannerPage() {...(enabledAddons.collab ? [{ id: 'collab', label: 'Collab' }] : []),]- const [activeTab, setActiveTab] = useState('plan')+ const [activeTab, setActiveTab] = useState(() => {+ const saved = sessionStorage.getItem(`trip-tab-${tripId}`)+ return saved || 'plan'+ })const handleTabChange = (tabId) => {setActiveTab(tabId)+ sessionStorage.setItem(`trip-tab-${tripId}`, tabId)if (tabId === 'finanzplan') tripStore.loadBudgetItems?.(tripId)if (tabId === 'dateien' && (!files || files.length === 0)) tripStore.loadFiles?.(tripId)}@@ -102,7 +107,8 @@ export default function TripPlannerPage() {const [showReservationModal, setShowReservationModal] = useState(false)const [editingReservation, setEditingReservation] = useState(null)const [route, setRoute] = useState(null)- const [routeInfo, setRouteInfo] = useState(null)+ const [routeInfo, setRouteInfo] = useState(null) // unused legacy+ const [routeSegments, setRouteSegments] = useState([]) // { from, to, walkingText, drivingText }const [fitKey, setFitKey] = useState(0)const [mobileSidebarOpen, setMobileSidebarOpen] = useState(null) // 'left' | 'right' | null@@ -130,9 +136,21 @@ export default function TripPlannerPage() {const handler = useTripStore.getState().handleRemoteEventjoinTrip(tripId)addListener(handler)+ // Reload files when collab notes change (attachments sync) — from WebSocket (other users)+ const collabFileSync = (event) => {+ if (event?.type === 'collab:note:deleted' || event?.type === 'collab:note:updated') {+ tripStore.loadFiles?.(tripId)+ }+ }+ addListener(collabFileSync)+ // Reload files when local collab actions change files (own user)+ const localFileSync = () => tripStore.loadFiles?.(tripId)+ window.addEventListener('collab-files-changed', localFileSync)return () => {leaveTrip(tripId)removeListener(handler)+ removeListener(collabFileSync)+ window.removeEventListener('collab-files-changed', localFileSync)}}, [tripId])@@ -167,17 +185,34 @@ export default function TripPlannerPage() {return places.filter(p => p.lat && p.lng)}, [places])- const updateRouteForDay = useCallback((dayId) => {- if (!dayId) { setRoute(null); setRouteInfo(null); return }+ const routeCalcEnabled = useSettingsStore(s => s.settings.route_calculation) !== false++ const updateRouteForDay = useCallback(async (dayId) => {+ if (!dayId) { setRoute(null); setRouteSegments([]); return }const da = (tripStore.assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)const waypoints = da.map(a => a.place).filter(p => p?.lat && p?.lng)if (waypoints.length >= 2) {setRoute(waypoints.map(p => [p.lat, p.lng]))+ if (!routeCalcEnabled) { setRouteSegments([]); return }+ // Calculate per-segment travel times+ const segments = []+ for (let i = 0; i < waypoints.length - 1; i++) {+ const from = [waypoints[i].lat, waypoints[i].lng]+ const to = [waypoints[i + 1].lat, waypoints[i + 1].lng]+ const mid = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]+ try {+ const result = await calculateRoute([{ lat: from[0], lng: from[1] }, { lat: to[0], lng: to[1] }], 'walking')+ segments.push({ mid, from, to, walkingText: result.walkingText, drivingText: result.drivingText })+ } catch {+ segments.push({ mid, from, to, walkingText: '?', drivingText: '?' })+ }+ }+ setRouteSegments(segments)} else {setRoute(null)+ setRouteSegments([])}- setRouteInfo(null)- }, [tripStore])+ }, [tripStore, routeCalcEnabled])const handleSelectDay = useCallback((dayId, skipFit) => {const changed = dayId !== selectedDayId@@ -411,6 +446,7 @@ export default function TripPlannerPage() {places={mapPlaces()}dayPlaces={dayPlaces}route={route}+ routeSegments={routeSegments}selectedPlaceId={selectedPlaceId}onMarkerClick={handleMarkerClick}onMapClick={handleMapClick}@@ -424,19 +460,6 @@ export default function TripPlannerPage() {hasInspector={!!selectedPlace}/>- {routeInfo && (- <div style={{- position: 'absolute', bottom: selectedPlace ? 180 : 20, left: '50%', transform: 'translateX(-50%)',- background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(20px)',- borderRadius: 99, padding: '6px 20px', zIndex: 30,- boxShadow: '0 2px 16px rgba(0,0,0,0.1)',- display: 'flex', gap: 12, fontSize: 13, color: '#374151',- }}>- <span>{routeInfo.distance}</span>- <span style={{ color: '#d1d5db' }}>·</span>- <span>{routeInfo.duration}</span>- </div>- )}<div className="hidden md:block" style={{ position: 'absolute', left: 10, top: 10, bottom: 10, zIndex: 20 }}><button onClick={() => setLeftCollapsed(c => !c)}@@ -479,7 +502,7 @@ export default function TripPlannerPage() {onReorder={handleReorder}onUpdateDayTitle={handleUpdateDayTitle}onAssignToDay={handleAssignToDay}- onRouteCalculated={(r) => { if (r) { setRoute(r.coordinates); setRouteInfo({ distance: r.distanceText, duration: r.durationText }) } else { setRoute(null); setRouteInfo(null) } }}+ onRouteCalculated={(r) => { if (r) { setRoute(r.coordinates); setRouteInfo({ distance: r.distanceText, duration: r.durationText, walkingText: r.walkingText, drivingText: r.drivingText }) } else { setRoute(null); setRouteInfo(null) } }}reservations={reservations}onAddReservation={(dayId) => { setEditingReservation(null); tripStore.setSelectedDay(dayId); setShowReservationModal(true) }}onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); setSelectedAssignmentId(null) }}@@ -696,8 +719,8 @@ export default function TripPlannerPage() {)}{activeTab === 'collab' && (- <div style={{ height: '100%', overflow: 'hidden', overscrollBehavior: 'contain' }}>- <CollabPanel tripId={tripId} />+ <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>+ <CollabPanel tripId={tripId} tripMembers={tripMembers} /></div>)}</div>diff --git a/server/package.json b/server/package.jsonindex e71bc8edf..db8bddcc2 100644--- a/server/package.json+++ b/server/package.json@@ -1,6 +1,6 @@{"name": "nomad-server",- "version": "2.5.7",+ "version": "2.6.0","main": "src/index.js","scripts": {"start": "node src/index.js",diff --git a/server/src/db/database.js b/server/src/db/database.jsindex be858596d..c65f5f999 100644--- a/server/src/db/database.js+++ b/server/src/db/database.js@@ -553,7 +553,7 @@ function initDb() {`);// Ensure collab addon exists for existing installationstry {- _db.prepare("INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', 0, 6)").run();+ _db.prepare("INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', 1, 6)").run();} catch {}},// 26: Per-assignment times (instead of shared place times)@@ -583,6 +583,29 @@ function initDb() {CREATE INDEX IF NOT EXISTS idx_budget_item_members_user ON budget_item_members(user_id);`);},+ // 28: Message reactions+ () => {+ _db.exec(`+ CREATE TABLE IF NOT EXISTS collab_message_reactions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ message_id INTEGER NOT NULL REFERENCES collab_messages(id) ON DELETE CASCADE,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ emoji TEXT NOT NULL,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,+ UNIQUE(message_id, user_id, emoji)+ );+ CREATE INDEX IF NOT EXISTS idx_collab_reactions_msg ON collab_message_reactions(message_id);+ `);+ },+ // 29: Soft-delete for chat messages+ () => {+ try { _db.exec('ALTER TABLE collab_messages ADD COLUMN deleted INTEGER DEFAULT 0'); } catch {}+ },+ // 30: Note attachments + website field+ () => {+ try { _db.exec('ALTER TABLE trip_files ADD COLUMN note_id INTEGER REFERENCES collab_notes(id) ON DELETE SET NULL'); } catch {}+ try { _db.exec('ALTER TABLE collab_notes ADD COLUMN website TEXT'); } catch {}+ },// Future migrations go here (append only, never reorder)];@@ -629,7 +652,7 @@ function initDb() {{ id: 'documents', name: 'Documents', description: 'Store and manage travel documents', type: 'trip', icon: 'FileText', enabled: 1, sort_order: 2 },{ id: 'vacay', name: 'Vacay', description: 'Personal vacation day planner with calendar view', type: 'global', icon: 'CalendarDays', enabled: 1, sort_order: 10 },{ id: 'atlas', name: 'Atlas', description: 'World map of your visited countries with travel stats', type: 'global', icon: 'Globe', enabled: 1, sort_order: 11 },- { id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 0, sort_order: 6 },+ { id: 'collab', name: 'Collab', description: 'Notes, polls, and live chat for trip collaboration', type: 'trip', icon: 'Users', enabled: 1, sort_order: 6 },];const insertAddon = _db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);diff --git a/server/src/routes/collab.js b/server/src/routes/collab.jsindex 350ff576c..242f10f52 100644--- a/server/src/routes/collab.js+++ b/server/src/routes/collab.js@@ -1,22 +1,68 @@const express = require('express');+const multer = require('multer');+const path = require('path');+const fs = require('fs');+const { v4: uuidv4 } = require('uuid');const { db, canAccessTrip } = require('../db/database');const { authenticate } = require('../middleware/auth');const { broadcast } = require('../websocket');+const filesDir = path.join(__dirname, '../../uploads/files');+const noteUpload = multer({+ storage: multer.diskStorage({+ destination: (req, file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir) },+ filename: (req, file, cb) => { cb(null, `${uuidv4()}${path.extname(file.originalname)}`) },+ }),+ limits: { fileSize: 50 * 1024 * 1024 },+});+const router = express.Router({ mergeParams: true });function verifyTripAccess(tripId, userId) {return canAccessTrip(tripId, userId);}+function avatarUrl(user) {+ return user.avatar ? `/uploads/avatars/${user.avatar}` : null;+}++function formatNote(note) {+ const attachments = db.prepare('SELECT id, filename, original_name, file_size, mime_type FROM trip_files WHERE note_id = ?').all(note.id);+ return {+ ...note,+ avatar_url: avatarUrl(note),+ attachments: attachments.map(a => ({ ...a, url: `/uploads/${a.filename}` })),+ };+}++function loadReactions(messageId) {+ return db.prepare(`+ SELECT r.emoji, r.user_id, u.username+ FROM collab_message_reactions r+ JOIN users u ON r.user_id = u.id+ WHERE r.message_id = ?+ `).all(messageId);+}++function groupReactions(reactions) {+ const map = {};+ for (const r of reactions) {+ if (!map[r.emoji]) map[r.emoji] = [];+ map[r.emoji].push({ user_id: r.user_id, username: r.username });+ }+ return Object.entries(map).map(([emoji, users]) => ({ emoji, users, count: users.length }));+}++function formatMessage(msg, reactions) {+ return { ...msg, user_avatar: avatarUrl(msg), avatar_url: avatarUrl(msg), reactions: reactions || [] };+}+// ─── NOTES ───────────────────────────────────────────────────────────────────-// GET /notes - list all notes for trip+// GET /notesrouter.get('/notes', authenticate, (req, res) => {const { tripId } = req.params;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const notes = db.prepare(`SELECT n.*, u.username, u.avatar@@ -26,42 +72,35 @@ router.get('/notes', authenticate, (req, res) => {ORDER BY n.pinned DESC, n.updated_at DESC`).all(tripId);- res.json({ notes });+ res.json({ notes: notes.map(formatNote) });});-// POST /notes - create note+// POST /notesrouter.post('/notes', authenticate, (req, res) => {const { tripId } = req.params;- const { title, content, category, color } = req.body;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });-+ const { title, content, category, color, website } = req.body;+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });if (!title) return res.status(400).json({ error: 'Title is required' });const result = db.prepare(`- INSERT INTO collab_notes (trip_id, user_id, title, content, category, color)- VALUES (?, ?, ?, ?, ?, ?)- `).run(tripId, req.user.id, title, content || null, category || 'General', color || '#6366f1');+ INSERT INTO collab_notes (trip_id, user_id, title, content, category, color, website)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ `).run(tripId, req.user.id, title, content || null, category || 'General', color || '#6366f1', website || null);const note = db.prepare(`- SELECT n.*, u.username, u.avatar- FROM collab_notes n- JOIN users u ON n.user_id = u.id- WHERE n.id = ?+ SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?`).get(result.lastInsertRowid);- res.status(201).json({ note });- broadcast(tripId, 'collab:note:created', { note }, req.headers['x-socket-id']);+ const formatted = formatNote(note);+ res.status(201).json({ note: formatted });+ broadcast(tripId, 'collab:note:created', { note: formatted }, req.headers['x-socket-id']);});-// PUT /notes/:id - update note+// PUT /notes/:idrouter.put('/notes/:id', authenticate, (req, res) => {const { tripId, id } = req.params;- const { title, content, category, color, pinned } = req.body;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ const { title, content, category, color, pinned, website } = req.body;+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const existing = db.prepare('SELECT * FROM collab_notes WHERE id = ? AND trip_id = ?').get(id, tripId);if (!existing) return res.status(404).json({ error: 'Note not found' });@@ -73,6 +112,7 @@ router.put('/notes/:id', authenticate, (req, res) => {category = COALESCE(?, category),color = COALESCE(?, color),pinned = CASE WHEN ? IS NOT NULL THEN ? ELSE pinned END,+ website = CASE WHEN ? THEN ? ELSE website END,updated_at = CURRENT_TIMESTAMPWHERE id = ?`).run(@@ -81,38 +121,77 @@ router.put('/notes/:id', authenticate, (req, res) => {category || null,color || null,pinned !== undefined ? 1 : null, pinned ? 1 : 0,+ website !== undefined ? 1 : 0, website !== undefined ? website : null,id);const note = db.prepare(`- SELECT n.*, u.username, u.avatar- FROM collab_notes n- JOIN users u ON n.user_id = u.id- WHERE n.id = ?+ SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?`).get(id);- res.json({ note });- broadcast(tripId, 'collab:note:updated', { note }, req.headers['x-socket-id']);+ const formatted = formatNote(note);+ res.json({ note: formatted });+ broadcast(tripId, 'collab:note:updated', { note: formatted }, req.headers['x-socket-id']);});-// DELETE /notes/:id - delete note+// DELETE /notes/:idrouter.delete('/notes/:id', authenticate, (req, res) => {const { tripId, id } = req.params;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const existing = db.prepare('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?').get(id, tripId);if (!existing) return res.status(404).json({ error: 'Note not found' });+ // Delete attached files (physical + DB)+ const noteFiles = db.prepare('SELECT id, filename FROM trip_files WHERE note_id = ?').all(id);+ for (const f of noteFiles) {+ const filePath = path.join(__dirname, '../../uploads', f.filename);+ try { fs.unlinkSync(filePath) } catch {}+ }+ db.prepare('DELETE FROM trip_files WHERE note_id = ?').run(id);+db.prepare('DELETE FROM collab_notes WHERE id = ?').run(id);res.json({ success: true });broadcast(tripId, 'collab:note:deleted', { noteId: Number(id) }, req.headers['x-socket-id']);});+// POST /notes/:id/files — upload attachment to note+router.post('/notes/:id/files', authenticate, noteUpload.single('file'), (req, res) => {+ const { tripId, id } = req.params;+ if (!verifyTripAccess(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });+ if (!req.file) return res.status(400).json({ error: 'No file uploaded' });++ const note = db.prepare('SELECT id FROM collab_notes WHERE id = ? AND trip_id = ?').get(id, tripId);+ if (!note) return res.status(404).json({ error: 'Note not found' });++ const result = db.prepare(+ 'INSERT INTO trip_files (trip_id, note_id, filename, original_name, file_size, mime_type) VALUES (?, ?, ?, ?, ?, ?)'+ ).run(tripId, id, `files/${req.file.filename}`, req.file.originalname, req.file.size, req.file.mimetype);++ const file = db.prepare('SELECT * FROM trip_files WHERE id = ?').get(result.lastInsertRowid);+ res.status(201).json({ file: { ...file, url: `/uploads/${file.filename}` } });+ broadcast(Number(tripId), 'collab:note:updated', { note: formatNote(db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(id)) }, req.headers['x-socket-id']);+});++// DELETE /notes/:id/files/:fileId — remove attachment+router.delete('/notes/:id/files/:fileId', authenticate, (req, res) => {+ const { tripId, id, fileId } = req.params;+ if (!verifyTripAccess(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });++ const file = db.prepare('SELECT * FROM trip_files WHERE id = ? AND note_id = ?').get(fileId, id);+ if (!file) return res.status(404).json({ error: 'File not found' });++ // Delete physical file+ const filePath = path.join(__dirname, '../../uploads', file.filename);+ try { fs.unlinkSync(filePath) } catch {}++ db.prepare('DELETE FROM trip_files WHERE id = ?').run(fileId);+ res.json({ success: true });+ broadcast(Number(tripId), 'collab:note:updated', { note: formatNote(db.prepare('SELECT n.*, u.username, u.avatar FROM collab_notes n JOIN users u ON n.user_id = u.id WHERE n.id = ?').get(id)) }, req.headers['x-socket-id']);+});+// ─── POLLS ───────────────────────────────────────────────────────────────────-// Helper: fetch a poll with aggregated votesfunction getPollWithVotes(pollId) {const poll = db.prepare(`SELECT p.*, u.username, u.avatar@@ -123,7 +202,7 @@ function getPollWithVotes(pollId) {if (!poll) return null;- poll.options = JSON.parse(poll.options);+ const options = JSON.parse(poll.options);const votes = db.prepare(`SELECT v.option_index, v.user_id, u.username, u.avatar@@ -132,73 +211,64 @@ function getPollWithVotes(pollId) {WHERE v.poll_id = ?`).all(pollId);- poll.votes = votes;- return poll;+ // Transform: nest voters into each option (frontend expects options[i].voters)+ const formattedOptions = options.map((label, idx) => ({+ label: typeof label === 'string' ? label : label.label || label,+ voters: votes+ .filter(v => v.option_index === idx)+ .map(v => ({ id: v.user_id, user_id: v.user_id, username: v.username, avatar: v.avatar, avatar_url: avatarUrl(v) })),+ }));++ return {+ ...poll,+ avatar_url: avatarUrl(poll),+ options: formattedOptions,+ is_closed: !!poll.closed,+ multiple_choice: !!poll.multiple,+ };}-// GET /polls - list all polls with votes+// GET /pollsrouter.get('/polls', authenticate, (req, res) => {const { tripId } = req.params;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const rows = db.prepare(`- SELECT p.*, u.username, u.avatar- FROM collab_polls p- JOIN users u ON p.user_id = u.id- WHERE p.trip_id = ?- ORDER BY p.created_at DESC+ SELECT id FROM collab_polls WHERE trip_id = ? ORDER BY created_at DESC`).all(tripId);- const polls = rows.map(poll => {- poll.options = JSON.parse(poll.options);-- const votes = db.prepare(`- SELECT v.option_index, v.user_id, u.username, u.avatar- FROM collab_poll_votes v- JOIN users u ON v.user_id = u.id- WHERE v.poll_id = ?- `).all(poll.id);-- poll.votes = votes;- return poll;- });-+ const polls = rows.map(row => getPollWithVotes(row.id)).filter(Boolean);res.json({ polls });});-// POST /polls - create poll+// POST /pollsrouter.post('/polls', authenticate, (req, res) => {const { tripId } = req.params;- const { question, options, multiple, deadline } = req.body;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });-+ const { question, options, multiple, multiple_choice, deadline } = req.body;+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });if (!question) return res.status(400).json({ error: 'Question is required' });if (!Array.isArray(options) || options.length < 2) {return res.status(400).json({ error: 'At least 2 options are required' });}+ // Accept both 'multiple' and 'multiple_choice' from frontend+ const isMultiple = multiple || multiple_choice;+const result = db.prepare(`INSERT INTO collab_polls (trip_id, user_id, question, options, multiple, deadline)VALUES (?, ?, ?, ?, ?, ?)- `).run(tripId, req.user.id, question, JSON.stringify(options), multiple ? 1 : 0, deadline || null);+ `).run(tripId, req.user.id, question, JSON.stringify(options), isMultiple ? 1 : 0, deadline || null);const poll = getPollWithVotes(result.lastInsertRowid);-res.status(201).json({ poll });broadcast(tripId, 'collab:poll:created', { poll }, req.headers['x-socket-id']);});-// POST /polls/:id/vote - toggle vote on poll+// POST /polls/:id/voterouter.post('/polls/:id/vote', authenticate, (req, res) => {const { tripId, id } = req.params;const { option_index } = req.body;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId);if (!poll) return res.status(404).json({ error: 'Poll not found' });@@ -217,27 +287,21 @@ router.post('/polls/:id/vote', authenticate, (req, res) => {if (existingVote) {db.prepare('DELETE FROM collab_poll_votes WHERE id = ?').run(existingVote.id);} else {- // If not multiple choice, remove any existing votes by this user firstif (!poll.multiple) {db.prepare('DELETE FROM collab_poll_votes WHERE poll_id = ? AND user_id = ?').run(id, req.user.id);}- db.prepare(- 'INSERT INTO collab_poll_votes (poll_id, user_id, option_index) VALUES (?, ?, ?)'- ).run(id, req.user.id, option_index);+ db.prepare('INSERT INTO collab_poll_votes (poll_id, user_id, option_index) VALUES (?, ?, ?)').run(id, req.user.id, option_index);}const updatedPoll = getPollWithVotes(id);-res.json({ poll: updatedPoll });broadcast(tripId, 'collab:poll:voted', { poll: updatedPoll }, req.headers['x-socket-id']);});-// PUT /polls/:id/close - close poll+// PUT /polls/:id/closerouter.put('/polls/:id/close', authenticate, (req, res) => {const { tripId, id } = req.params;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const poll = db.prepare('SELECT * FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId);if (!poll) return res.status(404).json({ error: 'Poll not found' });@@ -245,17 +309,14 @@ router.put('/polls/:id/close', authenticate, (req, res) => {db.prepare('UPDATE collab_polls SET closed = 1 WHERE id = ?').run(id);const updatedPoll = getPollWithVotes(id);-res.json({ poll: updatedPoll });broadcast(tripId, 'collab:poll:closed', { poll: updatedPoll }, req.headers['x-socket-id']);});-// DELETE /polls/:id - delete poll+// DELETE /polls/:idrouter.delete('/polls/:id', authenticate, (req, res) => {const { tripId, id } = req.params;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const poll = db.prepare('SELECT id FROM collab_polls WHERE id = ? AND trip_id = ?').get(id, tripId);if (!poll) return res.status(404).json({ error: 'Poll not found' });@@ -267,66 +328,61 @@ router.delete('/polls/:id', authenticate, (req, res) => {// ─── MESSAGES (CHAT) ────────────────────────────────────────────────────────-// GET /messages - list messages (last 100, with pagination via ?before=id)+// GET /messagesrouter.get('/messages', authenticate, (req, res) => {const { tripId } = req.params;const { before } = req.query;+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });-- let messages;- if (before) {- messages = db.prepare(`- SELECT m.*, u.username, u.avatar,- rm.text AS reply_text, ru.username AS reply_username- FROM collab_messages m- JOIN users u ON m.user_id = u.id- LEFT JOIN collab_messages rm ON m.reply_to = rm.id- LEFT JOIN users ru ON rm.user_id = ru.id- WHERE m.trip_id = ? AND m.id < ?- ORDER BY m.id DESC- LIMIT 100- `).all(tripId, before);- } else {- messages = db.prepare(`- SELECT m.*, u.username, u.avatar,- rm.text AS reply_text, ru.username AS reply_username- FROM collab_messages m- JOIN users u ON m.user_id = u.id- LEFT JOIN collab_messages rm ON m.reply_to = rm.id- LEFT JOIN users ru ON rm.user_id = ru.id- WHERE m.trip_id = ?- ORDER BY m.id DESC- LIMIT 100- `).all(tripId);- }+ const query = `+ SELECT m.*, u.username, u.avatar,+ rm.text AS reply_text, ru.username AS reply_username+ FROM collab_messages m+ JOIN users u ON m.user_id = u.id+ LEFT JOIN collab_messages rm ON m.reply_to = rm.id+ LEFT JOIN users ru ON rm.user_id = ru.id+ WHERE m.trip_id = ?${before ? ' AND m.id < ?' : ''}+ ORDER BY m.id DESC+ LIMIT 100+ `;- // Return in chronological order (oldest first)- messages.reverse();+ const messages = before+ ? db.prepare(query).all(tripId, before)+ : db.prepare(query).all(tripId);- res.json({ messages });+ messages.reverse();+ // Batch-load reactions+ const msgIds = messages.map(m => m.id);+ const reactionsByMsg = {};+ if (msgIds.length > 0) {+ const allReactions = db.prepare(`+ SELECT r.message_id, r.emoji, r.user_id, u.username+ FROM collab_message_reactions r+ JOIN users u ON r.user_id = u.id+ WHERE r.message_id IN (${msgIds.map(() => '?').join(',')})+ `).all(...msgIds);+ for (const r of allReactions) {+ if (!reactionsByMsg[r.message_id]) reactionsByMsg[r.message_id] = [];+ reactionsByMsg[r.message_id].push(r);+ }+ }+ res.json({ messages: messages.map(m => formatMessage(m, groupReactions(reactionsByMsg[m.id] || []))) });});-// POST /messages - send message+// POST /messagesrouter.post('/messages', authenticate, (req, res) => {const { tripId } = req.params;const { text, reply_to } = req.body;-- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });-+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });if (!text || !text.trim()) return res.status(400).json({ error: 'Message text is required' });- // Validate reply_to if providedif (reply_to) {const replyMsg = db.prepare('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?').get(reply_to, tripId);if (!replyMsg) return res.status(400).json({ error: 'Reply target message not found' });}const result = db.prepare(`- INSERT INTO collab_messages (trip_id, user_id, text, reply_to)- VALUES (?, ?, ?, ?)+ INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?, ?, ?, ?)`).run(tripId, req.user.id, text.trim(), reply_to || null);const message = db.prepare(`@@ -339,27 +395,92 @@ router.post('/messages', authenticate, (req, res) => {WHERE m.id = ?`).get(result.lastInsertRowid);- res.status(201).json({ message });- broadcast(tripId, 'collab:message:created', { message }, req.headers['x-socket-id']);+ const formatted = formatMessage(message);+ res.status(201).json({ message: formatted });+ broadcast(tripId, 'collab:message:created', { message: formatted }, req.headers['x-socket-id']);});-// DELETE /messages/:id - delete own message-router.delete('/messages/:id', authenticate, (req, res) => {+// POST /messages/:id/react — toggle emoji reaction+router.post('/messages/:id/react', authenticate, (req, res) => {const { tripId, id } = req.params;+ const { emoji } = req.body;+ if (!verifyTripAccess(Number(tripId), req.user.id)) return res.status(404).json({ error: 'Trip not found' });+ if (!emoji) return res.status(400).json({ error: 'Emoji is required' });++ const msg = db.prepare('SELECT id FROM collab_messages WHERE id = ? AND trip_id = ?').get(id, tripId);+ if (!msg) return res.status(404).json({ error: 'Message not found' });- const trip = verifyTripAccess(tripId, req.user.id);- if (!trip) return res.status(404).json({ error: 'Trip not found' });+ const existing = db.prepare('SELECT id FROM collab_message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?').get(id, req.user.id, emoji);+ if (existing) {+ db.prepare('DELETE FROM collab_message_reactions WHERE id = ?').run(existing.id);+ } else {+ db.prepare('INSERT INTO collab_message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(id, req.user.id, emoji);+ }++ const reactions = groupReactions(loadReactions(id));+ res.json({ reactions });+ broadcast(Number(tripId), 'collab:message:reacted', { messageId: Number(id), reactions }, req.headers['x-socket-id']);+});++// DELETE /messages/:id (soft-delete)+router.delete('/messages/:id', authenticate, (req, res) => {+ const { tripId, id } = req.params;+ if (!verifyTripAccess(tripId, req.user.id)) return res.status(404).json({ error: 'Trip not found' });const message = db.prepare('SELECT * FROM collab_messages WHERE id = ? AND trip_id = ?').get(id, tripId);if (!message) return res.status(404).json({ error: 'Message not found' });+ if (Number(message.user_id) !== Number(req.user.id)) return res.status(403).json({ error: 'You can only delete your own messages' });- if (message.user_id !== req.user.id) {- return res.status(403).json({ error: 'You can only delete your own messages' });- }-- db.prepare('DELETE FROM collab_messages WHERE id = ?').run(id);+ db.prepare('UPDATE collab_messages SET deleted = 1 WHERE id = ?').run(id);res.json({ success: true });- broadcast(tripId, 'collab:message:deleted', { messageId: Number(id) }, req.headers['x-socket-id']);+ broadcast(tripId, 'collab:message:deleted', { messageId: Number(id), username: message.username || req.user.username }, req.headers['x-socket-id']);+});++// ─── LINK PREVIEW ────────────────────────────────────────────────────────────++router.get('/link-preview', authenticate, (req, res) => {+ const { url } = req.query;+ if (!url) return res.status(400).json({ error: 'URL is required' });++ try {+ const fetch = require('node-fetch');+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 5000);++ fetch(url, {+ signal: controller.signal,+ headers: { 'User-Agent': 'Mozilla/5.0 (compatible; NOMAD/1.0; +https://github.com/mauriceboe/NOMAD)' },+ })+ .then(r => {+ clearTimeout(timeout);+ if (!r.ok) throw new Error('Fetch failed');+ return r.text();+ })+ .then(html => {+ const get = (prop) => {+ const m = html.match(new RegExp(`<meta[^>]*property=["']og:${prop}["'][^>]*content=["']([^"']*)["']`, 'i'))+ || html.match(new RegExp(`<meta[^>]*content=["']([^"']*)["'][^>]*property=["']og:${prop}["']`, 'i'));+ return m ? m[1] : null;+ };+ const titleTag = html.match(/<title[^>]*>([^<]*)<\/title>/i);+ const descMeta = html.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i)+ || html.match(/<meta[^>]*content=["']([^"']*)["'][^>]*name=["']description["']/i);++ res.json({+ title: get('title') || (titleTag ? titleTag[1].trim() : null),+ description: get('description') || (descMeta ? descMeta[1].trim() : null),+ image: get('image') || null,+ site_name: get('site_name') || null,+ url,+ });+ })+ .catch(() => {+ clearTimeout(timeout);+ res.json({ title: null, description: null, image: null, url });+ });+ } catch {+ res.json({ title: null, description: null, image: null, url });+ }});module.exports = router;diff --git a/server/src/routes/files.js b/server/src/routes/files.jsindex cf4c3feae..3df2c8d8d 100644--- a/server/src/routes/files.js+++ b/server/src/routes/files.js@@ -57,7 +57,7 @@ function verifyTripOwnership(tripId, userId) {function formatFile(file) {return {...file,- url: `/uploads/files/${file.filename}`,+ url: file.filename?.startsWith('files/') ? `/uploads/${file.filename}` : `/uploads/files/${file.filename}`,};}