Compare commits

...

35 Commits
main ... ai-dev

Author SHA1 Message Date
Flatlogic Bot
342070c5fa 07.03.2026 çalışan rota paylaşımlı 2026-03-06 21:15:50 +00:00
Flatlogic Bot
52bee4ac5d Edit app-9xzmfic2e4g1/src/pages/GuidesPage.tsx via Editor 2026-03-06 18:12:25 +00:00
Flatlogic Bot
20add55595 Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 18:11:58 +00:00
Flatlogic Bot
93b6e3d82d Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 17:50:25 +00:00
Flatlogic Bot
041650ebd6 Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 17:49:13 +00:00
Flatlogic Bot
cb048aa191 Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 17:47:26 +00:00
Flatlogic Bot
27a33044af Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 17:39:29 +00:00
Flatlogic Bot
2a52cdf8a5 Edit app-9xzmfic2e4g1/src/pages/GuideDetailPage.tsx via Editor 2026-03-06 17:38:53 +00:00
Flatlogic Bot
53461e923f Edit app-9xzmfic2e4g1/src/pages/GuidesPage.tsx via Editor 2026-03-06 17:38:29 +00:00
Flatlogic Bot
554a912a5e seyehat rehberi özelliği boş ekran 2026-03-06 15:25:06 +00:00
Flatlogic Bot
9e4c2baf15 Edit app-9xzmfic2e4g1/src/components/common/RouteGuard.tsx via Editor 2026-03-06 15:23:32 +00:00
Flatlogic Bot
d1b8576212 Edit app-9xzmfic2e4g1/src/components/layout/Navbar.tsx via Editor 2026-03-06 15:22:06 +00:00
Flatlogic Bot
306da112ab Edit app-9xzmfic2e4g1/src/routes.tsx via Editor 2026-03-06 15:21:08 +00:00
Flatlogic Bot
c5613c8077 Edit app-9xzmfic2e4g1/src/pages/TripDetailsPage.tsx via Editor 2026-03-06 15:19:49 +00:00
Flatlogic Bot
baae8a10d3 Edit app-9xzmfic2e4g1/src/pages/GuideDetailPage.tsx via Editor 2026-03-06 15:19:26 +00:00
Flatlogic Bot
f89537473a Edit app-9xzmfic2e4g1/src/pages/GuidesPage.tsx via Editor 2026-03-06 15:19:00 +00:00
Flatlogic Bot
af845fdc33 Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 15:18:11 +00:00
Flatlogic Bot
e84b6a9cd7 Edit app-9xzmfic2e4g1/src/pages/AccountPage.tsx via Editor 2026-03-06 14:20:06 +00:00
Flatlogic Bot
c06a3edc4b Edit app-9xzmfic2e4g1/src/pages/TripDetailsPage.tsx via Editor 2026-03-06 14:19:15 +00:00
Flatlogic Bot
51c739eb76 Edit app-9xzmfic2e4g1/src/components/trip/Timeline.tsx via Editor 2026-03-06 14:17:48 +00:00
Flatlogic Bot
764bc4a1e2 Edit app-9xzmfic2e4g1/src/components/trip/Map.tsx via Editor 2026-03-06 14:17:15 +00:00
Flatlogic Bot
f589c87d66 Edit app-9xzmfic2e4g1/src/components/trip/Map.tsx via Editor 2026-03-06 13:49:52 +00:00
Flatlogic Bot
fbad1021e0 Edit app-9xzmfic2e4g1/src/lib/google-maps-loader.ts via Editor 2026-03-06 13:49:02 +00:00
Flatlogic Bot
262f60e545 Edit app-9xzmfic2e4g1/src/components/trip/Map.tsx via Editor 2026-03-06 13:38:07 +00:00
Flatlogic Bot
fd27bbca46 Edit app-9xzmfic2e4g1/src/components/trip/Timeline.tsx via Editor 2026-03-06 13:21:24 +00:00
Flatlogic Bot
a517912861 Edit app-9xzmfic2e4g1/src/pages/PlannerPage.tsx via Editor 2026-03-06 12:58:50 +00:00
Flatlogic Bot
68fb947cda Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-06 12:57:29 +00:00
Flatlogic Bot
f00876fc81 Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-05 19:13:11 +00:00
Flatlogic Bot
7faea1370f Edit app-9xzmfic2e4g1/src/components/trip/Timeline.tsx via Editor 2026-03-05 19:12:40 +00:00
Flatlogic Bot
21a18c02e1 Edit app-9xzmfic2e4g1/.env via Editor 2026-03-05 18:39:30 +00:00
Flatlogic Bot
fada1b63a2 Edit app-9xzmfic2e4g1/src/constants/planner.ts via Editor 2026-03-05 18:04:26 +00:00
Flatlogic Bot
cdc4fc9abe Edit app-9xzmfic2e4g1/.env via Editor 2026-03-05 17:48:51 +00:00
Flatlogic Bot
8deb4450d6 yüklendi 2026-03-05 15:25:57 +00:00
Flatlogic Bot
827a0a1f77 Edit app-9xzmfic2e4g1/src/db/api.ts via Editor 2026-03-05 15:19:59 +00:00
Flatlogic Bot
79212cbccd Edit app-9xzmfic2e4g1/src/components/trip/Map.tsx via Editor 2026-03-05 15:19:34 +00:00
16 changed files with 1370 additions and 681 deletions

View File

@ -1,5 +1,5 @@
VITE_SUPABASE_URL=https://ofqojaxiopqxahfvxpmx.supabase.co VITE_SUPABASE_URL=https://bhaumxerateojqvleoyw.supabase.co
VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9mcW9qYXhpb3BxeGFoZnZ4cG14Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIyODExMjAsImV4cCI6MjA4Nzg1NzEyMH0.CVyjWPp9ldCd5qxA4TbViD5MJ0axbEWfGr-1n1pPjn0 VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJoYXVteGVyYXRlb2pxdmxlb3l3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjczNTQ4OTksImV4cCI6MjA4MjkzMDg5OX0.uyF3i17AaNd6CN5yWrGMR4vFsJ-boPrfKZYByXKBqUE
VITE_GOOGLE_MAPS_API_KEY=AIzaSyCLPiqNWwFSUS0X15YvTdHZxrb-2LXoYlw VITE_GOOGLE_MAPS_API_KEY=AIzaSyBbXWk7VhZfzn9txrAr9N-faAPuKy_LnKw
VITE_APP_ID=app-9xzmfic2e4g1 VITE_APP_ID=app-9xzmfic2e4g1
VITE_FORM_ID=form-9xzmfic2e4g1 VITE_FORM_ID=form-9xzmfic2e4g1

View File

@ -7,7 +7,7 @@ interface RouteGuardProps {
} }
// Please add the pages that can be accessed without logging in to PUBLIC_ROUTES. // Please add the pages that can be accessed without logging in to PUBLIC_ROUTES.
const PUBLIC_ROUTES = ['/login', '/403', '/404', '/', '/explore', '/planner']; const PUBLIC_ROUTES = ['/login', '/403', '/404', '/', '/explore', '/planner', '/rehberler', '/rehber/*'];
function matchPublicRoute(path: string, patterns: string[]) { function matchPublicRoute(path: string, patterns: string[]) {
return patterns.some(pattern => { return patterns.some(pattern => {

View File

@ -65,6 +65,12 @@ export function Navbar() {
> >
Planla Planla
</Link> </Link>
<Link
to="/rehberler"
className="text-sm font-medium text-muted-foreground hover:text-primary transition-colors"
>
Rehberler
</Link>
<Link <Link
to="/account" to="/account"
className="text-sm font-medium text-muted-foreground hover:text-primary transition-colors" className="text-sm font-medium text-muted-foreground hover:text-primary transition-colors"

View File

@ -20,7 +20,7 @@ export const BudgetSelector = memo(({ selectedId, onSelect }: BudgetSelectorProp
key={option.id} key={option.id}
className={cn( className={cn(
'h-1.5 flex-1 rounded-full transition-all duration-300', 'h-1.5 flex-1 rounded-full transition-all duration-300',
i <= selectedIndex ? option.dot : 'bg-gray-100' i <= selectedIndex ? option.bg : 'bg-gray-100'
)} )}
animate={{ scaleX: i <= selectedIndex ? 1 : 0.6 }} animate={{ scaleX: i <= selectedIndex ? 1 : 0.6 }}
transition={{ duration: 0.3, delay: i * 0.05 }} transition={{ duration: 0.3, delay: i * 0.05 }}
@ -46,7 +46,7 @@ export const BudgetSelector = memo(({ selectedId, onSelect }: BudgetSelectorProp
className={cn( className={cn(
'relative group flex items-center gap-4 px-5 py-4 rounded-2xl border-2 text-left transition-all duration-200 w-full overflow-hidden', 'relative group flex items-center gap-4 px-5 py-4 rounded-2xl border-2 text-left transition-all duration-200 w-full overflow-hidden',
isSelected isSelected
? `${option.activeBorder} ${option.activeBg} shadow-md` ? `${option.border} ${option.bg} shadow-md`
: 'border-gray-100 bg-gray-50/60 hover:border-gray-200 hover:bg-white hover:shadow-sm' : 'border-gray-100 bg-gray-50/60 hover:border-gray-200 hover:bg-white hover:shadow-sm'
)} )}
> >
@ -57,8 +57,8 @@ export const BudgetSelector = memo(({ selectedId, onSelect }: BudgetSelectorProp
key={i} key={i}
className={cn( className={cn(
'w-1.5 h-1.5 rounded-full transition-all duration-200', 'w-1.5 h-1.5 rounded-full transition-all duration-200',
i < option.tier i < 3
? isSelected ? option.dot : 'bg-gray-300' ? isSelected ? option.bg : 'bg-gray-300'
: 'bg-gray-100' : 'bg-gray-100'
)} )}
/> />
@ -69,7 +69,7 @@ export const BudgetSelector = memo(({ selectedId, onSelect }: BudgetSelectorProp
<div className={cn( <div className={cn(
'w-11 h-11 rounded-xl flex items-center justify-center transition-all duration-200 shrink-0', 'w-11 h-11 rounded-xl flex items-center justify-center transition-all duration-200 shrink-0',
isSelected isSelected
? `${option.activeBg} ${option.color} border-2 ${option.activeBorder}` ? `${option.bg} ${option.text} border-2 ${option.border}`
: 'bg-white text-gray-400 border border-gray-100 shadow-sm' : 'bg-white text-gray-400 border border-gray-100 shadow-sm'
)}> )}>
<Icon className="h-5 w-5" /> <Icon className="h-5 w-5" />
@ -79,7 +79,7 @@ export const BudgetSelector = memo(({ selectedId, onSelect }: BudgetSelectorProp
<div className="flex-1 min-w-0 pr-12"> <div className="flex-1 min-w-0 pr-12">
<p className={cn( <p className={cn(
'text-sm font-black uppercase tracking-wider', 'text-sm font-black uppercase tracking-wider',
isSelected ? option.color : 'text-gray-700' isSelected ? option.text : 'text-gray-700'
)}> )}>
{option.label} {option.label}
</p> </p>
@ -91,9 +91,9 @@ export const BudgetSelector = memo(({ selectedId, onSelect }: BudgetSelectorProp
{/* Price range */} {/* Price range */}
<div className={cn( <div className={cn(
'absolute bottom-3 right-4 text-[10px] font-bold tracking-wide transition-colors', 'absolute bottom-3 right-4 text-[10px] font-bold tracking-wide transition-colors',
isSelected ? option.color : 'text-gray-300' isSelected ? option.text : 'text-gray-300'
)}> )}>
{option.range} {option.description}
</div> </div>
</motion.button> </motion.button>
); );

View File

@ -32,7 +32,7 @@ interface PlaceDetail {
opening_hours?: string[] | null; opening_hours?: string[] | null;
why_visit: string[]; why_visit: string[];
tips: string[]; tips: string[];
reviews: { author: string; rating: number; text: string; time: string }[]; reviews: { author: string; rating: number | undefined; text: string; time: string }[];
} }
interface SelectedPOI { interface SelectedPOI {
@ -73,23 +73,85 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
setAdded(false); setAdded(false);
}, [itineraryKey]); }, [itineraryKey]);
// ── Fetch rich details ──────────────────────────────────────────────────── // ── Fetch rich details via Google Places API ─────────────────────────────
const fetchPlaceDetail = useCallback(async (poi: SelectedPOI) => { const fetchPlaceDetail = useCallback((poi: SelectedPOI) => {
if (!placesServiceRef.current) return;
setDetailLoading(true); setDetailLoading(true);
setPlaceDetail(null); setPlaceDetail(null);
setActiveTab('about'); setActiveTab('about');
try {
const data = await api.getPlaceDetails({ placesServiceRef.current.getDetails(
place_id: poi.place_id, {
name: poi.name, placeId: poi.place_id,
category: poi.category, fields: [
}); 'place_id', 'name', 'editorial_summary', 'rating', 'user_ratings_total',
setPlaceDetail(data); 'opening_hours', 'reviews', 'types', 'formatted_address',
} catch (e) { ],
console.error('Place detail fetch error:', e); language: 'tr',
} finally { } as any,
(place, status) => {
setDetailLoading(false); setDetailLoading(false);
if (status !== google.maps.places.PlacesServiceStatus.OK || !place) return;
const typeLabels: Record<string, string> = {
tourist_attraction: 'Turistik bir cazibe noktası — ziyaret değer.',
museum: 'Tarihi ve kültürel bir müze deneyimi sunar.',
restaurant: 'Yerel lezzetleri keşfetmek için harika bir mekan.',
park: 'Doğayla iç içe dinlenme ve yürüyüş imkânı.',
lodging: 'Konforlu konaklama seçeneği.',
natural_feature: 'Eşsiz doğal güzelliğiyle öne çıkan bir yer.',
church: 'Tarihi ve mimari açıdan ilgi çekici bir yapı.',
mosque: 'Tarihi ve mimari açıdan ilgi çekici bir yapı.',
point_of_interest: 'Bölgenin önemli ilgi noktalarından biri.',
};
// why_visit: önce AI'dan gelen poi.why_visit, yoksa tip etiketlerine bak
const whyVisit: string[] = [];
if ((poi as any).why_visit) {
whyVisit.push((poi as any).why_visit);
} else {
for (const t of (place.types || [])) {
const label = typeLabels[t];
if (label) { whyVisit.push(label); break; }
} }
}
// Tips: önce AI'dan gelen personal_tip, sonra Türkçe yorumlar
const tips: string[] = [];
if ((poi as any).personal_tip) {
tips.push((poi as any).personal_tip);
}
const reviewTips = (place.reviews || [])
.filter(r => (r.rating ?? 0) >= 4 && r.text?.length > 30)
.slice(0, tips.length > 0 ? 1 : 2)
.map(r => `"${r.text.slice(0, 120).trim()}…"`);
tips.push(...reviewTips);
// summary: editorial_summary sadece Türkçe ise göster, değilse boş bırak
const rawSummary = (place as any).editorial_summary?.overview || '';
const isTurkish = /[çğışöüÇĞİŞÖÜ]/.test(rawSummary) || !/[a-zA-Z]{4,}/.test(rawSummary);
const summary = isTurkish ? rawSummary : '';
const detail: PlaceDetail = {
place_id: place.place_id || poi.place_id,
name: place.name || poi.name,
summary,
rating: place.rating,
total_ratings: place.user_ratings_total,
is_open_now: place.opening_hours?.isOpen?.() ?? null,
opening_hours: place.opening_hours?.weekday_text || null,
why_visit: whyVisit,
tips,
reviews: (place.reviews || []).map(r => ({
author: r.author_name,
rating: r.rating,
text: r.text,
time: r.relative_time_description,
})),
};
setPlaceDetail(detail);
}
);
}, []); }, []);
// ── Handle add ──────────────────────────────────────────────────────────── // ── Handle add ────────────────────────────────────────────────────────────
@ -147,7 +209,7 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
placesServiceRef.current = new google.maps.places.PlacesService(map); placesServiceRef.current = new google.maps.places.PlacesService(map);
// ── POI tıklama ─────────────────────────────────────────────────── // ── POI tıklama ───────────────────────────────────────────────────
if (onAddPlace) { // POI tiklama - her zaman calisir, detay panelini acar
map.addListener('click', (e: google.maps.MapMouseEvent & { placeId?: string }) => { map.addListener('click', (e: google.maps.MapMouseEvent & { placeId?: string }) => {
if (!e.placeId) return; if (!e.placeId) return;
e.stop?.(); e.stop?.();
@ -155,12 +217,12 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
const placeId = e.placeId; const placeId = e.placeId;
setAdded(false); setAdded(false);
// Önce temel bilgiyi Google'dan çek, sonra panel aç
placesServiceRef.current?.getDetails( placesServiceRef.current?.getDetails(
{ {
placeId, placeId,
fields: ['place_id', 'name', 'formatted_address', 'geometry', 'rating', 'photos', 'types'], fields: ['place_id', 'name', 'formatted_address', 'geometry', 'rating', 'photos', 'types'],
}, language: 'tr',
} as any,
(place, status) => { (place, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK || !place?.geometry?.location) return; if (status !== google.maps.places.PlacesServiceStatus.OK || !place?.geometry?.location) return;
@ -183,7 +245,6 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
} }
); );
}); });
}
setGoogleMap(map); setGoogleMap(map);
} }
@ -205,7 +266,6 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
polylinesRef.current = []; polylinesRef.current = [];
const bounds = new google.maps.LatLngBounds(); const bounds = new google.maps.LatLngBounds();
const infoWindow = new google.maps.InfoWindow();
itinerary.days.forEach((day, dayIndex) => { itinerary.days.forEach((day, dayIndex) => {
const dayColor = DAY_COLORS[dayIndex % DAY_COLORS.length]; const dayColor = DAY_COLORS[dayIndex % DAY_COLORS.length];
@ -237,22 +297,27 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
marker.addListener('click', () => { marker.addListener('click', () => {
onMarkerClick(item.place_id); onMarkerClick(item.place_id);
// Sağ paneli aç — itinerary item'dan tüm veriyi taşı
const photoUrl = item.photo_reference const photoUrl = item.photo_reference
? (item.photo_reference.startsWith('http') ? item.photo_reference : api.getPhotoUrl(item.photo_reference)) ? (item.photo_reference.startsWith('http') ? item.photo_reference : api.getPhotoUrl(item.photo_reference))
: ''; : '';
infoWindow.setContent(`
<div style="padding:8px;min-width:200px;font-family:sans-serif;"> const poi: SelectedPOI & { why_visit?: string; personal_tip?: string } = {
${photoUrl ? `<img src="${photoUrl}" style="width:100%;height:90px;object-fit:cover;border-radius:8px;margin-bottom:8px;" />` : ''} place_id: item.place_id,
<h4 style="margin:0 0 2px;font-size:13px;font-weight:bold;">${item.name}</h4> name: item.name,
<p style="margin:0 0 6px;font-size:10px;color:#6B7280;">${item.category}</p> lat: item.lat,
<div style="display:flex;align-items:center;justify-content:space-between;"> lng: item.lng,
<span style="font-size:11px;font-weight:bold;color:#F59E0B;"> ${item.rating || 'N/A'}</span> photoUrl,
<a href="https://www.google.com/maps/dir/?api=1&destination=${item.lat},${item.lng}" target="_blank" category: item.category || 'point_of_interest',
style="color:#EA580C;font-size:11px;font-weight:bold;text-decoration:none;">Yol Tarifi </a> formatted_address: item.formatted_address || '',
</div> rating: item.rating ?? undefined,
</div> why_visit: (item as any).why_visit,
`); personal_tip: (item as any).personal_tip,
infoWindow.open(googleMap, marker); };
setSelectedPOI(poi);
fetchPlaceDetail(poi);
}); });
markersRef.current[item.place_id] = { marker, dayIndex }; markersRef.current[item.place_id] = { marker, dayIndex };
@ -504,14 +569,14 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
)} )}
{/* Çalışma saatleri */} {/* Çalışma saatleri */}
{placeDetail.opening_hours?.length > 0 && ( {(placeDetail.opening_hours?.length ?? 0) > 0 && (
<div className="space-y-2"> <div className="space-y-2">
<h4 className="text-[11px] font-black text-gray-900 uppercase tracking-widest flex items-center gap-1.5"> <h4 className="text-[11px] font-black text-gray-900 uppercase tracking-widest flex items-center gap-1.5">
<Clock className="h-3.5 w-3.5 text-blue-500" /> <Clock className="h-3.5 w-3.5 text-blue-500" />
Çalışma Saatleri Çalışma Saatleri
</h4> </h4>
<div className="space-y-1"> <div className="space-y-1">
{placeDetail.opening_hours.map((h, i) => ( {(placeDetail.opening_hours ?? []).map((h, i) => (
<p key={i} className="text-[11px] text-gray-500">{h}</p> <p key={i} className="text-[11px] text-gray-500">{h}</p>
))} ))}
</div> </div>
@ -542,7 +607,7 @@ export function TripMap({ itinerary, activePlaceId, onMarkerClick, onAddPlace }:
<div className="flex items-center gap-0.5"> <div className="flex items-center gap-0.5">
{[1,2,3,4,5].map(s => ( {[1,2,3,4,5].map(s => (
<Star key={s} <Star key={s}
className={cn('h-3 w-3', s <= review.rating className={cn('h-3 w-3', s <= (review.rating ?? 0)
? 'fill-amber-400 text-amber-400' ? 'fill-amber-400 text-amber-400'
: 'text-gray-200 fill-gray-200' : 'text-gray-200 fill-gray-200'
)} )}

View File

@ -160,6 +160,16 @@ function DaySection({
)} )}
</div> </div>
{/* Day story — AI hikayesi */}
{day.day_story && (
<div className="mx-1 flex items-start gap-2.5 px-3 py-2.5 bg-gradient-to-r from-orange-50 to-amber-50 border border-orange-100 rounded-xl">
<Wand2 className="h-3.5 w-3.5 text-orange-500 shrink-0 mt-0.5" />
<p className="text-[12px] text-orange-800 font-medium leading-relaxed italic">
{day.day_story}
</p>
</div>
)}
{/* Empty state */} {/* Empty state */}
{day.items.length === 0 && ( {day.items.length === 0 && (
<div className="mx-2 py-12 flex flex-col items-center gap-3 border-2 border-dashed border-gray-100 rounded-2xl bg-gray-50/50"> <div className="mx-2 py-12 flex flex-col items-center gap-3 border-2 border-dashed border-gray-100 rounded-2xl bg-gray-50/50">
@ -236,28 +246,8 @@ function DaySection({
</DndContext> </DndContext>
)} )}
{/* AI suggestion card */}
<div className="mx-2">
<div className="bg-gradient-to-br from-orange-50 to-amber-50 border border-orange-100 rounded-2xl p-4 space-y-3 relative overflow-hidden group">
<div className="absolute -right-3 -top-3 opacity-5">
<Wand2 className="h-20 w-20 text-orange-600" />
</div>
<div className="flex items-center gap-2">
<span className="text-xs font-black text-orange-800">Akıllı Tur Önerisi</span>
<Badge className="bg-orange-100 text-orange-600 hover:bg-orange-100 border-0 text-[9px] font-black">%82 Uyum</Badge>
</div>
<p className="text-[11px] text-gray-600 leading-relaxed">
Planınız Green Tour rotasıyla %82 uyumlu. Yeraltı şehri ve Ihlara Vadisi eklenebilir.
</p>
<Button className="w-full bg-orange-600 hover:bg-orange-700 h-8 rounded-xl text-[10px] font-black gap-1.5">
<Wand2 className="h-3.5 w-3.5" />
Seçenekleri İncele
</Button>
</div>
</div>
{/* Add place search */} {/* Add place search */}
<div className="mx-2"> <div className="mx-2" id={`place-search-day-${dayIndex}`}>
<PlaceSearch <PlaceSearch
onPlaceSelect={place => onAddPlace(dayIndex, place)} onPlaceSelect={place => onAddPlace(dayIndex, place)}
placeholder="Yeni bir durak ekle..." placeholder="Yeni bir durak ekle..."
@ -295,11 +285,24 @@ function SortableItem({
}; };
const photoUrl = useMemo(() => { const photoUrl = useMemo(() => {
if (!item.photo_reference) return null; if (item.photo_reference) {
return item.photo_reference.startsWith('http') return item.photo_reference.startsWith('http')
? item.photo_reference ? item.photo_reference
: api.getPhotoUrl(item.photo_reference); : api.getPhotoUrl(item.photo_reference);
}, [item.photo_reference]); }
// Kategori bazlı Kapadokya fallback resimleri
const fallbacks: Record<string, string> = {
museum: 'https://images.unsplash.com/photo-1599930113854-d6d7fd521f10?w=400&q=80',
nature: 'https://images.unsplash.com/photo-1570168007204-dfb528c6958f?w=400&q=80',
history: 'https://images.unsplash.com/photo-1524231757912-21f4fe3a7200?w=400&q=80',
landmark: 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=400&q=80',
gastronomy: 'https://images.unsplash.com/photo-1512152272829-e3139592d56f?w=400&q=80',
culture: 'https://images.unsplash.com/photo-1599930113854-d6d7fd521f10?w=400&q=80',
activity: 'https://images.unsplash.com/photo-1570168007204-dfb528c6958f?w=400&q=80',
wellness: 'https://images.unsplash.com/photo-1544833316-64d88e00182a?w=400&q=80',
};
return fallbacks[item.category] ?? 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=400&q=80';
}, [item.photo_reference, item.category]);
const endTime = calcEndTime(item); const endTime = calcEndTime(item);
@ -351,24 +354,24 @@ function SortableItem({
</div> </div>
</div> </div>
{/* Küçük thumbnail */} {/* Küçük thumbnail — her zaman göster */}
{photoUrl && !imgError && (
<div className="relative w-16 h-16 rounded-xl overflow-hidden bg-gray-100 shrink-0"> <div className="relative w-16 h-16 rounded-xl overflow-hidden bg-gray-100 shrink-0">
{!imgLoaded && ( {!imgLoaded && (
<div className="absolute inset-0 bg-gradient-to-r from-gray-200 via-gray-100 to-gray-200 animate-pulse" /> <div className="absolute inset-0 bg-gradient-to-r from-gray-200 via-gray-100 to-gray-200 animate-pulse" />
)} )}
<img <img
src={photoUrl} src={imgError
? 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=400&q=80'
: photoUrl}
alt={item.name} alt={item.name}
onLoad={() => setImgLoaded(true)} onLoad={() => setImgLoaded(true)}
onError={() => setImgError(true)} onError={() => { setImgError(true); setImgLoaded(true); }}
className={cn( className={cn(
"w-full h-full object-cover transition-opacity duration-300", "w-full h-full object-cover transition-opacity duration-300",
imgLoaded ? "opacity-100" : "opacity-0" imgLoaded ? "opacity-100" : "opacity-0"
)} )}
/> />
</div> </div>
)}
{/* Aksiyonlar (hover'da görünür) */} {/* Aksiyonlar (hover'da görünür) */}
<div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-all shrink-0"> <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-all shrink-0">
@ -437,6 +440,22 @@ function SortableItem({
<p className="text-[11px] font-medium italic text-orange-800">{item.notes}</p> <p className="text-[11px] font-medium italic text-orange-800">{item.notes}</p>
</div> </div>
)} )}
{/* why_visit — neden bu yer */}
{item.why_visit && (
<div className="mt-2 flex items-start gap-2 px-2 py-1.5 bg-blue-50 rounded-lg border border-blue-100">
<MapPin className="h-3 w-3 text-blue-500 shrink-0 mt-0.5" />
<p className="text-[11px] text-blue-700 font-medium leading-snug">{item.why_visit}</p>
</div>
)}
{/* personal_tip — kişisel ipucu */}
{item.personal_tip && (
<div className="mt-1.5 flex items-start gap-2 px-2 py-1.5 bg-amber-50 rounded-lg border border-amber-100">
<Star className="h-3 w-3 text-amber-500 shrink-0 mt-0.5" />
<p className="text-[11px] text-amber-700 font-medium leading-snug">{item.personal_tip}</p>
</div>
)}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>

View File

@ -1,529 +1,243 @@
import { useState, useMemo, useCallback, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import api from '@/db/api';
import { Label } from '@/components/ui/label';
import { Form, FormField, FormItem, FormMessage } from '@/components/ui/form';
import { toast } from 'sonner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod';
import { format, differenceInDays } from 'date-fns';
import { import {
Loader2, ArrowRight, ArrowLeft, Sparkles, User, Users, Heart, Compass,
MapPin, Calendar, Users, Coffee, Heart, Car, Bus, Shuffle, Navigation,
Car, Wallet, CheckCircle2, ChevronRight, Wallet, CreditCard, Star, Crown,
PersonStanding, Tent, Building2, Home, Castle,
TreePine, Landmark, Camera,
Zap, UtensilsCrossed, Wind,
CheckCircle2, Sparkles, Flame, MapPin,
} from 'lucide-react'; } from 'lucide-react';
import { parseApiError } from '@/utils/errorHandler';
import { retryWithBackoff, withTimeout } from '@/utils/retryWithBackoff';
import { motion, AnimatePresence } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { LOADING_STEPS, TRAVEL_TYPE_OPTIONS, BUDGET_OPTIONS, TRANSPORT_OPTIONS, ACCOMMODATION_OPTIONS, INTEREST_OPTIONS } from '@/constants/planner'; // ─── Travel Types ─────────────────────────────────────────────────────────────
import { DateSelector } from '@/components/planner/DateSelector'; export const TRAVEL_TYPE_OPTIONS = [
import { TravelerInput } from '@/components/planner/TravelerInput'; {
import { AccommodationSelector } from '@/components/planner/AccommodationSelector'; id: 'solo',
import { InterestsGrid } from '@/components/planner/InterestsGrid'; label: 'Yalnız',
import { TravelTypeSelector } from '@/components/planner/TravelTypeSelector'; description: 'Özgür, bağımsız keşif',
import { TransportSelector } from '@/components/planner/TransportSelector'; icon: User,
import { BudgetSelector } from '@/components/planner/BudgetSelector'; bg: 'bg-violet-50',
border: 'border-violet-400',
// ─── Schema ─────────────────────────────────────────────────────────────────── text: 'text-violet-600',
const formSchema = z.object({ gradient: 'from-violet-500 to-purple-600',
dateRange: z.object({
from: z.date({ required_error: 'Başlangıç tarihi gereklidir' }),
to: z.date({ required_error: 'Bitiş tarihi gereklidir' }),
})
.refine(d => d.from >= new Date(new Date().setHours(0, 0, 0, 0)), {
message: 'Başlangıç tarihi bugünden önce olamaz',
})
.refine(d => d.to > d.from, {
message: 'Bitiş tarihi başlangıç tarihinden sonra olmalıdır',
})
.refine(d => {
const days = differenceInDays(d.to, d.from) + 1;
return days >= 1 && days <= 14;
}, { message: 'Seyahat süresi 114 gün arasında olmalıdır' }),
travelType: z.string().min(1, 'Seyahat tipi seçiniz'),
travelers: z.number().min(1).max(15),
accommodation: z.string(),
transport: z.string().min(1, 'Ulaşım tercihi seçiniz'),
budget: z.string().min(1, 'Bütçe aralığı seçiniz'),
interests: z.array(z.string()).min(1, 'En az 1 ilgi alanı seçiniz').max(6),
});
type FormValues = z.infer<typeof formSchema>;
// ─── Steps ────────────────────────────────────────────────────────────────────
const STEPS = [
{ id: 'dates', title: 'Tarihler', icon: Calendar, description: 'Ne zaman gidiyorsunuz?' },
{ id: 'travelType', title: 'Seyahat Tipi', icon: PersonStanding, description: 'Nasıl bir seyahat?' },
{ id: 'travelers', title: 'Grup & Konaklama', icon: Users, description: 'Kiminle, nerede kalıyorsunuz?' },
{ id: 'transport', title: 'Ulaşım', icon: Car, description: 'Nasıl seyahat edeceksiniz?' },
{ id: 'budget', title: 'Bütçe', icon: Wallet, description: 'Ne kadar harcamayı planlıyorsunuz?' },
{ id: 'interests', title: 'İlgi Alanları', icon: Heart, description: 'Neleri keşfetmek istersiniz?' },
] as const;
// ─── Summary label helpers ────────────────────────────────────────────────────
function getSummaryLabel(stepId: string, values: Partial<FormValues>): string | null {
switch (stepId) {
case 'dates':
if (values.dateRange?.from && values.dateRange?.to)
return `${format(values.dateRange.from, 'd MMM')} ${format(values.dateRange.to, 'd MMM')}`;
return null;
case 'travelType':
return TRAVEL_TYPE_OPTIONS.find(o => o.id === values.travelType)?.label ?? null;
case 'travelers':
return values.travelers ? `${values.travelers} kişi` : null;
case 'transport':
return TRANSPORT_OPTIONS.find(o => o.id === values.transport)?.label ?? null;
case 'budget':
return BUDGET_OPTIONS.find(o => o.id === values.budget)?.label ?? null;
case 'interests':
return values.interests?.length ? `${values.interests.length} seçildi` : null;
default:
return null;
}
}
// ─── PlannerPage ──────────────────────────────────────────────────────────────
const PlannerPage = () => {
const { user } = useAuth();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [loadingStep, setLoadingStep] = useState(0);
const [currentStep, setCurrentStep] = useState(0);
const [datePickerOpen, setDatePickerOpen] = useState(false);
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
dateRange: { from: undefined, to: undefined },
travelType: '',
travelers: 2,
accommodation: 'center',
transport: '',
budget: '',
interests: [],
}, },
}); {
id: 'couple',
label: 'Çift',
description: 'Romantik kaçamak',
icon: Heart,
bg: 'bg-rose-50',
border: 'border-rose-400',
text: 'text-rose-600',
gradient: 'from-rose-500 to-pink-600',
},
{
id: 'family',
label: 'Aile',
description: 'Herkese uygun aktiviteler',
icon: Users,
bg: 'bg-amber-50',
border: 'border-amber-400',
text: 'text-amber-600',
gradient: 'from-amber-500 to-orange-600',
},
{
id: 'friends',
label: 'Arkadaşlar',
description: 'Macera & eğlence dolu',
icon: Compass,
bg: 'bg-emerald-50',
border: 'border-emerald-400',
text: 'text-emerald-600',
gradient: 'from-emerald-500 to-teal-600',
},
];
const watchedValues = form.watch(); // ─── Transport Options ────────────────────────────────────────────────────────
export const TRANSPORT_OPTIONS = [
{
id: 'rental',
label: 'Kiralık Araç',
description: 'En özgür seçenek, uzak noktalara ulaşım',
icon: Car,
bg: 'bg-blue-50',
border: 'border-blue-400',
text: 'text-blue-600',
gradient: 'from-blue-500 to-indigo-600',
},
{
id: 'transfer',
label: 'Özel Transfer',
description: 'Konforlu, planlı güzergahlar',
icon: Navigation,
bg: 'bg-purple-50',
border: 'border-purple-400',
text: 'text-purple-600',
gradient: 'from-purple-500 to-violet-600',
},
{
id: 'shuttle',
label: 'Servis / Minibüs',
description: 'Popüler turist güzergahları',
icon: Bus,
bg: 'bg-orange-50',
border: 'border-orange-400',
text: 'text-orange-600',
gradient: 'from-orange-500 to-amber-600',
},
{
id: 'mixed',
label: 'Karma',
description: 'Esnek kombinasyon',
icon: Shuffle,
bg: 'bg-teal-50',
border: 'border-teal-400',
text: 'text-teal-600',
gradient: 'from-teal-500 to-cyan-600',
},
];
// ── Navigation ────────────────────────────────────────────────────────────── // ─── Budget Options ───────────────────────────────────────────────────────────
const nextStep = async () => { export const BUDGET_OPTIONS = [
const stepId = STEPS[currentStep].id; {
const fieldMap: Record<string, keyof FormValues | (keyof FormValues)[]> = { id: 'budget',
dates: 'dateRange', label: 'Ekonomik',
travelType: 'travelType', description: '₺5001.000 / gün',
travelers: ['travelers', 'accommodation'], icon: Wallet,
transport: 'transport', bg: 'bg-green-50',
budget: 'budget', border: 'border-green-400',
interests: 'interests', text: 'text-green-600',
}; gradient: 'from-green-500 to-emerald-600',
const fields = fieldMap[stepId]; },
const isValid = await form.trigger(Array.isArray(fields) ? fields : [fields]); {
if (isValid && currentStep < STEPS.length - 1) setCurrentStep(p => p + 1); id: 'moderate',
}; label: 'Orta',
description: '₺1.0002.500 / gün',
icon: CreditCard,
bg: 'bg-sky-50',
border: 'border-sky-400',
text: 'text-sky-600',
gradient: 'from-sky-500 to-blue-600',
},
{
id: 'comfort',
label: 'Konforlu',
description: '₺2.5005.000 / gün',
icon: Star,
bg: 'bg-amber-50',
border: 'border-amber-400',
text: 'text-amber-600',
gradient: 'from-amber-500 to-yellow-600',
},
{
id: 'luxury',
label: 'Lüks',
description: '₺5.000+ / gün',
icon: Crown,
bg: 'bg-rose-50',
border: 'border-rose-400',
text: 'text-rose-600',
gradient: 'from-rose-500 to-pink-600',
},
];
const prevStep = () => { if (currentStep > 0) setCurrentStep(p => p - 1); }; // ─── Accommodation Options ────────────────────────────────────────────────────
export const ACCOMMODATION_OPTIONS = [
{
id: 'cave',
label: 'Mağara Otel',
description: 'Eşsiz Kapadokya deneyimi',
icon: Castle,
},
{
id: 'center',
label: 'Merkez Otel',
description: 'Göreme veya Ürgüp merkezi',
icon: Building2,
},
{
id: 'boutique',
label: 'Butik Otel',
description: 'Küçük, şık tesisler',
icon: Home,
},
{
id: 'camping',
label: 'Kamp',
description: 'Doğayla iç içe',
icon: Tent,
},
];
const handleInterestToggle = useCallback((id: string) => { // ─── Interest Options ─────────────────────────────────────────────────────────
const current = form.getValues('interests'); export const INTEREST_OPTIONS = [
const next = current.includes(id) ? current.filter(i => i !== id) : [...current, id]; {
form.setValue('interests', next, { shouldValidate: true }); id: 'balloon',
}, [form]); label: 'Balon Turu',
description: 'Şafakta gökyüzü',
icon: Wind,
bg: 'bg-sky-50',
border: 'border-sky-300',
text: 'text-sky-600',
gradient: 'from-sky-400 to-blue-500',
},
{
id: 'nature',
label: 'Doğa & Yürüyüş',
description: 'Vadiler ve izler',
icon: TreePine,
bg: 'bg-emerald-50',
border: 'border-emerald-300',
text: 'text-emerald-600',
gradient: 'from-emerald-400 to-green-500',
},
{
id: 'history',
label: 'Tarih & Kültür',
description: 'Yeraltı şehirleri, kiliseler',
icon: Landmark,
bg: 'bg-amber-50',
border: 'border-amber-300',
text: 'text-amber-600',
gradient: 'from-amber-400 to-orange-500',
},
{
id: 'photography',
label: 'Fotoğrafçılık',
description: 'En iyi manzara noktaları',
icon: Camera,
bg: 'bg-violet-50',
border: 'border-violet-300',
text: 'text-violet-600',
gradient: 'from-violet-400 to-purple-500',
},
{
id: 'adventure',
label: 'Macera',
description: 'ATV, atçılık, zipline',
icon: Zap,
bg: 'bg-orange-50',
border: 'border-orange-300',
text: 'text-orange-600',
gradient: 'from-orange-400 to-red-500',
},
{
id: 'gastronomy',
label: 'Gastronomi',
description: 'Yerel mutfak, şarap tadımı',
icon: UtensilsCrossed,
bg: 'bg-rose-50',
border: 'border-rose-300',
text: 'text-rose-600',
gradient: 'from-rose-400 to-pink-500',
},
];
const simulateLoadingSteps = useCallback(() => { // ─── Loading Steps ────────────────────────────────────────────────────────────
setLoadingStep(0); export const LOADING_STEPS = [
const iv = setInterval(() => { { label: 'Tercihleriniz analiz ediliyor...', progress: 15, icon: Sparkles },
setLoadingStep(prev => { { label: 'AI rotanızı oluşturuyor...', progress: 35, icon: Flame },
if (prev < LOADING_STEPS.length - 1) return prev + 1; { label: 'Google Maps ile doğrulanıyor...', progress: 55, icon: MapPin },
clearInterval(iv); { label: 'Fotoğraflar ve detaylar yükleniyor...', progress: 75, icon: Camera },
return prev; { label: 'Güzergahlar hesaplanıyor...', progress: 90, icon: Navigation },
}); { label: 'Rotanız hazırlanıyor!', progress: 100, icon: CheckCircle2 },
}, 2500); ];
return iv;
}, []);
// ── Submit ──────────────────────────────────────────────────────────────────
const onSubmit = async (data: FormValues) => {
setLoading(true);
const iv = simulateLoadingSteps();
try {
const startDate = format(data.dateRange.from, 'yyyy-MM-dd');
const endDate = format(data.dateRange.to, 'yyyy-MM-dd');
const result = await retryWithBackoff(
() => withTimeout(
api.generateItinerary({
startDate, endDate,
interests: data.interests,
dailySchedule: 'moderate',
preferences: `Type:${data.travelType}, Accommodation:${data.accommodation}, Transport:${data.transport}, Budget:${data.budget}, Travelers:${data.travelers}`,
}),
45000,
new Error('Sunucu yanıt vermiyor, lütfen tekrar deneyin.')
),
{ maxRetries: 2, initialDelay: 1000, maxDelay: 5000 }
);
clearInterval(iv);
if (user) {
const saved = await api.saveTrip({
user_id: user.id,
title: 'Kapadokya Gezisi',
destination: 'Cappadocia',
start_date: startDate,
end_date: endDate,
preferences: { startDate, endDate, interests: data.interests, dailySchedule: 'moderate', preferences: '' },
itinerary: result,
});
navigate(`/trip/${saved.id}`);
toast.success('Rotanız hazır!');
} else {
sessionStorage.setItem('pending_trip', JSON.stringify(result));
navigate('/login', { state: { from: '/planner', message: 'Planınızı kaydetmek için giriş yapın' } });
}
} catch (err) {
clearInterval(iv);
if (err instanceof Error && err.name === 'AbortError') return;
toast.error('Hata oluştu', { description: parseApiError(err).userMessage });
} finally {
setLoading(false);
setLoadingStep(0);
}
};
const progress = ((currentStep + 1) / STEPS.length) * 100;
// ── Loading screen ──────────────────────────────────────────────────────────
if (loading) {
return (
<div className="h-screen w-full flex flex-col items-center justify-center bg-secondary relative overflow-hidden">
<div className="absolute inset-0 opacity-15">
<img
src="https://images.unsplash.com/photo-1541167760496-1628856ab772?auto=format&fit=crop&q=80&w=2400"
alt=""
className="w-full h-full object-cover grayscale"
/>
</div>
<div className="absolute inset-0 bg-secondary/60" />
<div className="relative z-10 max-w-md w-full px-8 text-center space-y-10">
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
className="relative mx-auto w-24 h-24"
>
<div className="absolute inset-0 bg-primary rounded-2xl animate-pulse opacity-30 scale-110" />
<div className="w-24 h-24 bg-primary rounded-2xl flex items-center justify-center shadow-2xl shadow-primary/30">
<Loader2 className="h-11 w-11 text-white animate-spin" />
</div>
</motion.div>
<div className="space-y-5">
<AnimatePresence mode="wait">
<motion.h2
key={loadingStep}
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -12 }}
className="text-3xl font-black text-white tracking-tighter uppercase"
>
{LOADING_STEPS[loadingStep].label}
</motion.h2>
</AnimatePresence>
<div className="w-full h-2 bg-white/10 rounded-full overflow-hidden">
<motion.div
className="h-full bg-primary rounded-full"
initial={{ width: 0 }}
animate={{ width: `${LOADING_STEPS[loadingStep].progress}%` }}
transition={{ duration: 0.6, ease: 'easeInOut' }}
/>
</div>
<div className="flex justify-between text-[10px] font-bold text-white/30 uppercase tracking-widest px-1">
<span>Hazırlanıyor</span>
<span>{LOADING_STEPS[loadingStep].progress}%</span>
</div>
</div>
<p className="text-white/30 text-xs font-medium italic">
Size özel Kapadokya efsanesi kurguluyoruz...
</p>
</div>
</div>
);
}
// ── Main layout ─────────────────────────────────────────────────────────────
return (
<div className="min-h-screen bg-background flex flex-col lg:flex-row overflow-hidden">
{/* ── Sidebar ─────────────────────────────────────────────────────────── */}
<div className="w-full lg:w-[300px] xl:w-[360px] bg-secondary flex flex-col relative overflow-hidden shrink-0">
{/* Decorative orbs */}
<div className="absolute top-0 left-0 w-72 h-72 bg-primary/10 rounded-full blur-3xl -translate-x-1/2 -translate-y-1/2 pointer-events-none" />
<div className="absolute bottom-0 right-0 w-64 h-64 bg-accent/5 rounded-full blur-3xl translate-x-1/3 translate-y-1/3 pointer-events-none" />
<div className="relative z-10 flex flex-col h-full p-8 lg:p-10 gap-8">
{/* Logo */}
<div className="flex items-center gap-3">
<div className="w-9 h-9 bg-primary rounded-xl flex items-center justify-center text-white shadow-lg shadow-primary/20">
<MapPin className="h-4 w-4" />
</div>
<span className="text-base font-black text-white tracking-tight uppercase">
Kapadokya <span className="text-primary">Efsanesi</span>
</span>
</div>
{/* Headline */}
<div className="space-y-2">
<h1 className="text-3xl xl:text-4xl font-black text-white leading-none tracking-tighter uppercase">
ROTANIZI<br /><span className="text-primary">TASARLAYIN</span>
</h1>
<p className="text-white/35 text-sm font-medium italic">
"Size özel kurgulanmış seyahat mimarisi."
</p>
</div>
{/* Step list */}
<div className="flex-1 space-y-1.5">
{STEPS.map((step, i) => {
const Icon = step.icon;
const isActive = i === currentStep;
const isCompleted = i < currentStep;
const summaryLabel = getSummaryLabel(step.id, watchedValues);
return (
<motion.div
key={step.id}
animate={{ opacity: isActive || isCompleted ? 1 : 0.35 }}
className={cn(
'flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-200 group',
isActive && 'bg-white/8'
)}
>
{/* Step indicator */}
<div className={cn(
'w-8 h-8 rounded-lg flex items-center justify-center shrink-0 transition-all duration-300',
isActive ? 'bg-primary text-white shadow-md shadow-primary/30 scale-110'
: isCompleted ? 'bg-white/10 text-primary'
: 'bg-white/5 text-white/20'
)}>
{isCompleted
? <CheckCircle2 className="h-4 w-4" />
: <Icon className="h-4 w-4" />
}
</div>
{/* Labels */}
<div className="flex-1 min-w-0">
<div className={cn(
'text-[9px] font-black uppercase tracking-[0.15em]',
isActive ? 'text-primary' : 'text-white/25'
)}>
{String(i + 1).padStart(2, '0')}
</div>
<div className={cn(
'text-sm font-bold leading-tight truncate',
isActive ? 'text-white' : isCompleted ? 'text-white/60' : 'text-white/30'
)}>
{step.title}
</div>
</div>
{/* Summary pill */}
{isCompleted && summaryLabel && (
<span className="text-[9px] font-black text-primary/70 bg-primary/10 px-2 py-0.5 rounded-full shrink-0 max-w-[80px] truncate">
{summaryLabel}
</span>
)}
{isActive && (
<ChevronRight className="h-3.5 w-3.5 text-primary/60 shrink-0" />
)}
</motion.div>
);
})}
</div>
{/* Progress bar */}
<div className="space-y-2 pt-2 border-t border-white/8">
<div className="flex justify-between text-[10px] font-bold text-white/25 uppercase tracking-widest">
<span>İlerleme</span>
<span>{Math.round(progress)}%</span>
</div>
<div className="h-1 bg-white/8 rounded-full overflow-hidden">
<motion.div
className="h-full bg-primary rounded-full"
animate={{ width: `${progress}%` }}
transition={{ duration: 0.5, ease: 'easeOut' }}
/>
</div>
</div>
</div>
</div>
{/* ── Main Form Area ──────────────────────────────────────────────────── */}
<div className="flex-1 bg-white dark:bg-card overflow-y-auto">
<div className="max-w-2xl mx-auto min-h-full flex flex-col px-8 py-10 lg:py-14 lg:px-16">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex-1 flex flex-col">
<AnimatePresence mode="wait">
<motion.div
key={currentStep}
initial={{ opacity: 0, x: 24 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -24 }}
transition={{ duration: 0.35, ease: 'easeOut' }}
className="flex-1 space-y-10"
>
{/* Step header */}
<div className="space-y-2">
<div className="flex items-center gap-2 text-[10px] font-black text-primary uppercase tracking-[0.2em]">
<span>Adım {currentStep + 1}/{STEPS.length}</span>
<span className="w-12 h-0.5 bg-primary/20 rounded-full" />
<span>{STEPS[currentStep].title}</span>
</div>
<h2 className="text-3xl md:text-4xl xl:text-5xl font-black text-gray-900 dark:text-white tracking-tighter leading-[0.95] uppercase">
{STEPS[currentStep].description}
</h2>
</div>
{/* Step content */}
<div className="pt-2">
{/* Step 0 — Dates */}
{currentStep === 0 && (
<FormField control={form.control} name="dateRange" render={({ field }) => (
<FormItem className="space-y-3">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">Seyahat Takvimi</Label>
<DateSelector
date={field.value}
onDateChange={field.onChange}
isOpen={datePickerOpen}
onOpenChange={setDatePickerOpen}
/>
<FormMessage />
</FormItem>
)} />
)}
{/* Step 1 — Travel Type */}
{currentStep === 1 && (
<FormField control={form.control} name="travelType" render={({ field }) => (
<FormItem className="space-y-3">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">Seyahat Tarzı</Label>
<TravelTypeSelector selectedId={field.value} onSelect={field.onChange} />
<FormMessage />
</FormItem>
)} />
)}
{/* Step 2 — Travelers & Accommodation */}
{currentStep === 2 && (
<div className="space-y-8">
<FormField control={form.control} name="travelers" render={({ field }) => (
<FormItem className="space-y-3">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">Grup Büyüklüğü</Label>
<TravelerInput value={field.value} onChange={field.onChange} />
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name="accommodation" render={({ field }) => (
<FormItem className="space-y-3">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">Konaklama Tarzı</Label>
<AccommodationSelector selectedId={field.value} onSelect={field.onChange} />
<FormMessage />
</FormItem>
)} />
</div>
)}
{/* Step 3 — Transport */}
{currentStep === 3 && (
<FormField control={form.control} name="transport" render={({ field }) => (
<FormItem className="space-y-3">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">Ulaşım Tercihi</Label>
<TransportSelector selectedId={field.value} onSelect={field.onChange} />
<FormMessage />
</FormItem>
)} />
)}
{/* Step 4 — Budget */}
{currentStep === 4 && (
<FormField control={form.control} name="budget" render={({ field }) => (
<FormItem className="space-y-3">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">Günlük Bütçe</Label>
<BudgetSelector selectedId={field.value} onSelect={field.onChange} />
<FormMessage />
</FormItem>
)} />
)}
{/* Step 5 — Interests */}
{currentStep === 5 && (
<FormField control={form.control} name="interests" render={({ field }) => (
<FormItem className="space-y-3">
<div className="flex justify-between items-center">
<Label className="text-[10px] font-black uppercase tracking-[0.2em] text-primary">İlgi Alanları</Label>
<span className="text-[10px] font-bold text-gray-400">{field.value.length}/6 Seçildi</span>
</div>
<InterestsGrid selectedInterests={field.value} onToggle={handleInterestToggle} />
<FormMessage />
</FormItem>
)} />
)}
</div>
</motion.div>
</AnimatePresence>
{/* Navigation */}
<div className="pt-10 mt-auto flex items-center justify-between gap-4 border-t border-gray-100 dark:border-white/8">
<Button
type="button"
variant="ghost"
size="lg"
onClick={prevStep}
disabled={currentStep === 0}
className="h-13 px-7 text-sm font-bold rounded-xl hover:bg-gray-50 group disabled:opacity-30"
>
<ArrowLeft className="mr-2 h-4 w-4 group-hover:-translate-x-1 transition-transform" />
Geri
</Button>
{currentStep < STEPS.length - 1 ? (
<Button
type="button"
size="lg"
onClick={nextStep}
className="h-13 px-10 text-sm font-black bg-primary hover:bg-primary/90 rounded-xl shadow-lg shadow-primary/20 group uppercase tracking-widest"
>
Devam Et
<ArrowRight className="ml-2 h-4 w-4 group-hover:translate-x-1 transition-transform" />
</Button>
) : (
<Button
type="submit"
size="lg"
className="h-13 px-12 text-sm font-black bg-primary hover:bg-primary/90 rounded-xl shadow-lg shadow-primary/20 uppercase tracking-widest"
>
Rotayı Oluştur
<Sparkles className="ml-2 h-4 w-4 animate-pulse" />
</Button>
)}
</div>
</form>
</Form>
</div>
</div>
</div>
);
};
export default memo(PlannerPage);

View File

@ -14,6 +14,8 @@ export interface Place {
start_time: string; start_time: string;
end_time: string; end_time: string;
notes?: string; notes?: string;
personal_tip?: string;
why_visit?: string;
} }
export interface ItineraryDay { export interface ItineraryDay {
@ -22,6 +24,7 @@ export interface ItineraryDay {
total_distance?: string; total_distance?: string;
total_duration?: string; total_duration?: string;
notes?: string; notes?: string;
day_story?: string;
} }
export interface Trip { export interface Trip {
@ -37,7 +40,6 @@ export interface Trip {
} }
const api = { const api = {
// Trips
async getTrips() { async getTrips() {
const { data, error } = await supabase const { data, error } = await supabase
.from('trips') .from('trips')
@ -86,7 +88,6 @@ const api = {
if (error) throw error; if (error) throw error;
}, },
// Edge Functions
async generateItinerary(params: { async generateItinerary(params: {
startDate: string; startDate: string;
endDate: string; endDate: string;
@ -97,7 +98,7 @@ const api = {
transport: string; transport: string;
budget: string; budget: string;
travelers: number; travelers: number;
}) { }): Promise<{ days: any[]; ai_used: boolean; ai_error: string | null }> {
const { data, error } = await supabase.functions.invoke('generate-itinerary', { const { data, error } = await supabase.functions.invoke('generate-itinerary', {
body: params, body: params,
}); });
@ -121,10 +122,103 @@ const api = {
}, },
getPhotoUrl(photoReference: string) { getPhotoUrl(photoReference: string) {
const { data } = supabase.storage.from('dummy').getPublicUrl('dummy'); // Just to get the base URL const { data } = supabase.storage.from('dummy').getPublicUrl('dummy');
const baseUrl = data.publicUrl.split('/storage/v1')[0]; const baseUrl = data.publicUrl.split('/storage/v1')[0];
return `${baseUrl}/functions/v1/get-place-photo?photo_reference=${photoReference}`; return `${baseUrl}/functions/v1/get-place-photo?photo_reference=${photoReference}`;
},
async publishGuide(tripId: string, opts: {
guide_intro?: string;
guide_tips?: string[];
}) {
const { data, error } = await supabase
.from('trips')
.update({
is_public: true,
guide_intro: opts.guide_intro || null,
guide_tips: opts.guide_tips || [],
published_at: new Date().toISOString(),
})
.eq('id', tripId)
.select()
.single();
if (error) throw error;
return data;
},
async unpublishGuide(tripId: string) {
const { error } = await supabase
.from('trips')
.update({ is_public: false, published_at: null })
.eq('id', tripId);
if (error) throw error;
},
async getPublicGuides(limit = 20) {
const { data, error } = await supabase
.from('trips')
.select('id, title, destination, start_date, end_date, itinerary, guide_intro, guide_tips, views_count, likes_count, published_at, user_id')
.eq('is_public', true)
.order('likes_count', { ascending: false })
.order('views_count', { ascending: false })
.limit(limit);
if (error) throw error;
return data || [];
},
async getPublicGuide(tripId: string) {
const { data, error } = await supabase
.from('trips')
.select('*')
.eq('id', tripId)
.eq('is_public', true)
.single();
if (error) throw error;
supabase.rpc('increment_guide_views', { trip_id: tripId }).then(() => {});
return data;
},
async cloneGuide(tripId: string): Promise<Trip> {
const guide = await this.getPublicGuide(tripId);
if (!guide) throw new Error('Rehber bulunamadı');
const newTrip = await this.saveTrip({
title: `${guide.title} (Kopyam)`,
destination: guide.destination,
start_date: guide.start_date,
end_date: guide.end_date,
preferences: guide.preferences,
itinerary: guide.itinerary,
});
return newTrip;
},
async toggleLike(tripId: string): Promise<boolean> {
const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error('Giriş gerekli');
const { data: existing } = await supabase
.from('guide_likes')
.select('user_id')
.eq('user_id', user.id)
.eq('trip_id', tripId)
.maybeSingle();
if (existing) {
await supabase.from('guide_likes').delete().eq('user_id', user.id).eq('trip_id', tripId);
return false;
} else {
await supabase.from('guide_likes').insert({ user_id: user.id, trip_id: tripId });
return true;
} }
},
async getMyLikes(): Promise<string[]> {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return [];
const { data } = await supabase
.from('guide_likes')
.select('trip_id')
.eq('user_id', user.id);
return (data || []).map((r: any) => r.trip_id);
},
}; };
export default api; export default api;

View File

@ -3,9 +3,8 @@ let isInitialized = false;
export const initGoogleMaps = async (apiKey: string) => { export const initGoogleMaps = async (apiKey: string) => {
if (isInitialized) return; if (isInitialized) return;
// Dynamically load the Google Maps script
const script = document.createElement('script'); const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&v=weekly`; script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&v=weekly&language=tr&region=TR`;
script.async = true; script.async = true;
script.defer = true; script.defer = true;

View File

@ -144,11 +144,24 @@ export default function AccountPage() {
<CardContent className="p-0"> <CardContent className="p-0">
<div className="flex flex-col sm:flex-row"> <div className="flex flex-col sm:flex-row">
<div className="sm:w-56 h-48 sm:h-auto bg-gray-200 relative overflow-hidden shrink-0"> <div className="sm:w-56 h-48 sm:h-auto bg-gray-200 relative overflow-hidden shrink-0">
{(() => {
const firstItem = trip.itinerary?.days?.[0]?.items?.[0];
const photoSrc = firstItem?.photo_reference
? (firstItem.photo_reference.startsWith('http')
? firstItem.photo_reference
: api.getPhotoUrl(firstItem.photo_reference))
: 'https://images.unsplash.com/photo-1541167760496-1628856ab772?auto=format&fit=crop&q=80&w=800';
return (
<img <img
src="https://images.unsplash.com/photo-1541167760496-1628856ab772?auto=format&fit=crop&q=80&w=2400" src={photoSrc}
alt={trip.title} alt={trip.title}
className="w-full h-full object-cover group-hover:scale-105 transition-luxury duration-700" className="w-full h-full object-cover group-hover:scale-105 transition-luxury duration-700"
onError={(e) => {
(e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1541167760496-1628856ab772?auto=format&fit=crop&q=80&w=800';
}}
/> />
);
})()}
<div className="absolute top-4 left-4"> <div className="absolute top-4 left-4">
<Badge className="bg-primary text-white border-none font-black px-2 py-0.5 rounded-full uppercase text-[8px]"> <Badge className="bg-primary text-white border-none font-black px-2 py-0.5 rounded-full uppercase text-[8px]">
<Zap className="h-2 w-2 mr-1" /> <Zap className="h-2 w-2 mr-1" />
@ -205,9 +218,14 @@ export default function AccountPage() {
{trip.itinerary.days[0].items.slice(0, 3).map((item, i) => ( {trip.itinerary.days[0].items.slice(0, 3).map((item, i) => (
<div key={i} className="w-10 h-10 rounded-xl border-2 border-white dark:border-secondary bg-gray-100 overflow-hidden shadow-md"> <div key={i} className="w-10 h-10 rounded-xl border-2 border-white dark:border-secondary bg-gray-100 overflow-hidden shadow-md">
<img <img
src={item.photo_reference ? (item.photo_reference.startsWith('http') ? item.photo_reference : api.getPhotoUrl(item.photo_reference)) : 'https://via.placeholder.com/100'} src={item.photo_reference
? (item.photo_reference.startsWith('http') ? item.photo_reference : api.getPhotoUrl(item.photo_reference))
: 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=100&q=80'}
alt="" alt=""
className="w-full h-full object-cover" className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=100&q=80';
}}
/> />
</div> </div>
))} ))}

View File

@ -0,0 +1,364 @@
import { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import api from '@/db/api';
import { TripMap } from '@/components/trip/Map';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { motion, AnimatePresence } from 'framer-motion';
import {
Heart, Eye, MapPin, Calendar, Copy, Loader2,
ChevronLeft, Clock, Lightbulb, User, ChevronDown, ChevronUp
} from 'lucide-react';
import { format, addDays, differenceInDays } from 'date-fns';
import { tr } from 'date-fns/locale';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
const DAY_COLORS = ['#EA580C', '#9333EA', '#2563EB', '#059669', '#D97706'];
export default function GuideDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { user } = useAuth();
const [guide, setGuide] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [cloning, setCloning] = useState(false);
const [liked, setLiked] = useState(false);
const [selectedDay, setSelectedDay] = useState(0);
const [activePlaceId, setActivePlaceId] = useState<string | null>(null);
const [tipsExpanded, setTipsExpanded] = useState(false);
useEffect(() => {
if (!id) return;
load();
}, [id]);
const load = async () => {
try {
const [data, likes] = await Promise.all([
api.getPublicGuide(id!),
user ? api.getMyLikes() : Promise.resolve([]),
]);
setGuide(data);
setLiked(likes.includes(id!));
} catch {
toast.error('Rehber bulunamadı');
navigate('/rehberler');
} finally {
setLoading(false);
}
};
const handleLike = async () => {
if (!user) { navigate('/login'); return; }
const wasLiked = liked;
setLiked(!wasLiked);
setGuide((g: any) => ({ ...g, likes_count: g.likes_count + (wasLiked ? -1 : 1) }));
try { await api.toggleLike(id!); }
catch { setLiked(wasLiked); }
};
const handleClone = async () => {
if (!user) { navigate('/login'); return; }
setCloning(true);
try {
const newTrip = await api.cloneGuide(id!);
toast.success('Rota kopyalandı! Düzenlemeye başlayabilirsiniz.');
navigate(`/trip/${newTrip.id}`);
} catch {
toast.error('Kopyalama başarısız');
} finally {
setCloning(false);
}
};
const getCoverPhoto = () => {
const first = guide?.itinerary?.days?.[0]?.items?.[0];
if (first?.photo_reference) {
return first.photo_reference.startsWith('http')
? first.photo_reference
: api.getPhotoUrl(first.photo_reference);
}
return 'https://images.unsplash.com/photo-1570168007204-dfb528c6958f?auto=format&fit=crop&q=80&w=1600';
};
const getDayDate = (idx: number) => {
if (!guide?.start_date) return `Gün ${idx + 1}`;
try {
return format(addDays(new Date(guide.start_date), idx), 'd MMM', { locale: tr });
} catch { return `Gün ${idx + 1}`; }
};
const getTripDuration = () => {
if (!guide?.start_date || !guide?.end_date) return null;
try {
return differenceInDays(new Date(guide.end_date), new Date(guide.start_date)) + 1;
} catch { return null; }
};
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Loader2 className="h-10 w-10 animate-spin text-primary opacity-40" />
</div>
);
}
if (!guide) return null;
const days = guide.itinerary?.days || [];
const currentDay = days[selectedDay];
const tips: string[] = guide.guide_tips || [];
const duration = getTripDuration();
return (
<div className="min-h-screen bg-background">
{/* Hero */}
<div className="relative h-80 md:h-[420px] overflow-hidden bg-gray-900">
<img
src={getCoverPhoto()}
alt={guide.title}
className="w-full h-full object-cover opacity-70"
onError={(e) => {
(e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=1600&q=80';
}}
/>
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />
<button onClick={() => navigate('/rehberler')}
className="absolute top-6 left-6 flex items-center gap-2 text-white/80 hover:text-white text-xs font-bold transition-colors bg-black/20 backdrop-blur-sm rounded-full px-3 py-1.5">
<ChevronLeft className="h-3.5 w-3.5" /> Rehberler
</button>
<div className="absolute bottom-0 left-0 right-0 p-6 md:p-10">
<div className="max-w-4xl mx-auto">
<div className="flex flex-wrap gap-2 mb-3">
{duration && (
<Badge className="bg-orange-600 text-white border-0 font-black text-[9px] px-2.5">
{duration} GÜN
</Badge>
)}
<Badge className="bg-white/20 text-white border-0 backdrop-blur-sm font-black text-[9px] px-2.5">
{days.reduce((s: number, d: any) => s + (d.items?.length || 0), 0)} DURAK
</Badge>
{guide.destination && (
<Badge className="bg-white/20 text-white border-0 backdrop-blur-sm font-black text-[9px] px-2.5">
📍 {guide.destination}
</Badge>
)}
</div>
<h1 className="text-3xl md:text-5xl font-black text-white tracking-tighter leading-tight mb-3">
{guide.title}
</h1>
<div className="flex items-center gap-4 text-white/60 text-xs font-bold">
{guide.profiles?.full_name && (
<span className="flex items-center gap-1.5">
<User className="h-3.5 w-3.5" />
{guide.profiles.full_name}
</span>
)}
{guide.published_at && (
<span className="flex items-center gap-1.5">
<Calendar className="h-3.5 w-3.5" />
{format(new Date(guide.published_at), 'd MMMM yyyy', { locale: tr })}
</span>
)}
<span className="flex items-center gap-1.5">
<Eye className="h-3.5 w-3.5" />
{guide.views_count || 0} görüntülenme
</span>
</div>
</div>
</div>
</div>
{/* Sticky CTA bar */}
<div className="sticky top-16 z-30 bg-white/95 backdrop-blur-md border-b shadow-sm">
<div className="max-w-4xl mx-auto px-6 h-14 flex items-center justify-between gap-4">
<div className="flex items-center gap-3">
<button onClick={handleLike}
className={cn(
'flex items-center gap-1.5 text-xs font-bold transition-all px-3 py-1.5 rounded-full',
liked
? 'bg-red-50 text-red-600'
: 'text-gray-400 hover:text-red-500 hover:bg-red-50'
)}>
<Heart className={cn('h-4 w-4', liked && 'fill-current')} />
{guide.likes_count || 0}
</button>
</div>
<Button onClick={handleClone} disabled={cloning}
className="h-9 px-6 rounded-xl bg-orange-600 hover:bg-orange-700 font-black text-xs gap-2">
{cloning ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Copy className="h-3.5 w-3.5" />}
Bu Planı Kullan
</Button>
</div>
</div>
<div className="max-w-4xl mx-auto px-6 py-8 space-y-8">
{guide.guide_intro && (
<motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }}
className="bg-orange-50 border border-orange-100 rounded-2xl p-5">
<p className="text-xs font-black text-orange-700 uppercase tracking-widest mb-2">Gezgin Notu</p>
<p className="text-sm text-gray-700 leading-relaxed italic">"{guide.guide_intro}"</p>
</motion.div>
)}
{tips.length > 0 && (
<div className="bg-gray-50 rounded-2xl p-5 space-y-3">
<button
onClick={() => setTipsExpanded(!tipsExpanded)}
className="w-full flex items-center justify-between">
<div className="flex items-center gap-2">
<Lightbulb className="h-4 w-4 text-amber-500" />
<span className="text-sm font-black text-gray-900">Genel İpuçları</span>
<Badge className="bg-amber-100 text-amber-700 border-0 text-[9px] font-black">
{tips.length} ipucu
</Badge>
</div>
{tipsExpanded ? <ChevronUp className="h-4 w-4 text-gray-400" /> : <ChevronDown className="h-4 w-4 text-gray-400" />}
</button>
<AnimatePresence>
{tipsExpanded && (
<motion.ul
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
className="space-y-2 overflow-hidden">
{tips.map((tip, i) => (
<li key={i} className="flex items-start gap-2.5 text-sm text-gray-600">
<span className="w-5 h-5 rounded-full bg-amber-100 text-amber-700 flex items-center justify-center text-[10px] font-black shrink-0 mt-0.5">
{i + 1}
</span>
{tip}
</li>
))}
</motion.ul>
)}
</AnimatePresence>
</div>
)}
<div className="space-y-4">
<div className="flex gap-2 overflow-x-auto pb-1">
{days.map((day: any, idx: number) => (
<button
key={idx}
onClick={() => setSelectedDay(idx)}
className={cn(
'flex flex-col items-center px-4 py-2.5 rounded-xl transition-all shrink-0 min-w-[72px]',
selectedDay === idx
? 'text-white shadow-lg'
: 'bg-gray-100 text-gray-500 hover:bg-gray-200'
)}
style={selectedDay === idx ? { backgroundColor: DAY_COLORS[idx % DAY_COLORS.length] } : {}}
>
<span className="text-[9px] font-black uppercase tracking-wider">Gün {day.day}</span>
<span className="text-[8px] font-semibold opacity-70 mt-0.5">{getDayDate(idx)}</span>
<Badge className={cn(
'mt-1 text-[7px] px-1.5 h-3.5 font-black border-0',
selectedDay === idx ? 'bg-white/25 text-white' : 'bg-gray-200 text-gray-400'
)}>
{day.items?.length || 0}
</Badge>
</button>
))}
</div>
{currentDay && (
<div className="grid lg:grid-cols-2 gap-6">
<div className="space-y-3">
{(currentDay.items || []).map((item: any, idx: number) => (
<motion.div
key={item.place_id}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: idx * 0.06 }}
onClick={() => setActivePlaceId(item.place_id)}
className={cn(
'flex gap-3 p-3 rounded-2xl border-2 cursor-pointer transition-all',
activePlaceId === item.place_id
? 'border-orange-400 bg-orange-50'
: 'border-gray-100 bg-white hover:border-orange-200'
)}
>
<div className="w-7 h-7 rounded-xl flex items-center justify-center text-white text-[11px] font-black shrink-0 mt-0.5"
style={{ backgroundColor: DAY_COLORS[selectedDay % DAY_COLORS.length] }}>
{idx + 1}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<h4 className="text-sm font-black text-gray-900 leading-tight">{item.name}</h4>
{item.rating && (
<span className="text-[10px] font-black text-amber-600 shrink-0">
{item.rating}
</span>
)}
</div>
{item.start_time && (
<p className="text-[10px] font-bold text-gray-400 mt-0.5 flex items-center gap-1">
<Clock className="h-2.5 w-2.5" />
{item.start_time} {item.end_time}
</p>
)}
{item.why_visit && (
<p className="text-[11px] text-blue-700 mt-1.5 leading-snug flex items-start gap-1">
<MapPin className="h-3 w-3 shrink-0 mt-0.5 text-blue-500" />
{item.why_visit}
</p>
)}
{item.personal_tip && (
<p className="text-[11px] text-amber-700 mt-1 leading-snug flex items-start gap-1">
<Lightbulb className="h-3 w-3 shrink-0 mt-0.5 text-amber-500" />
{item.personal_tip}
</p>
)}
</div>
{item.photo_reference && (
<div className="w-14 h-14 rounded-xl overflow-hidden shrink-0">
<img
src={item.photo_reference.startsWith('http') ? item.photo_reference : api.getPhotoUrl(item.photo_reference)}
alt={item.name}
className="w-full h-full object-cover"
onError={(e) => { (e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=200&q=80'; }}
/>
</div>
)}
</motion.div>
))}
</div>
<div className="h-96 lg:h-auto lg:min-h-[400px] rounded-3xl overflow-hidden shadow-xl">
<TripMap
itinerary={{ days: [currentDay] }}
activePlaceId={activePlaceId}
onMarkerClick={setActivePlaceId}
/>
</div>
</div>
)}
</div>
<div className="bg-gradient-to-br from-orange-50 to-amber-50 border border-orange-100 rounded-3xl p-8 text-center space-y-4">
<h3 className="text-2xl font-black text-gray-900 tracking-tight">Bu rotayı beğendiniz mi?</h3>
<p className="text-gray-500 text-sm italic">Bir tıkla kendi planınıza kopyalayın ve özelleştirin.</p>
<Button onClick={handleClone} disabled={cloning}
className="h-12 px-10 rounded-xl bg-orange-600 hover:bg-orange-700 font-black gap-2 shadow-lg">
{cloning ? <Loader2 className="h-4 w-4 animate-spin" /> : <Copy className="h-4 w-4" />}
Bu Planı Kullan
</Button>
{!user && (
<p className="text-xs text-gray-400">
Kopyalamak için{' '}
<Link to="/login" className="text-orange-600 font-bold hover:underline">giriş yapın</Link>
</p>
)}
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,228 @@
import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import api from '@/db/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { motion } from 'framer-motion';
import { Heart, Eye, MapPin, Calendar, ArrowRight, Compass, Loader2 } from 'lucide-react';
import { format } from 'date-fns';
import { tr } from 'date-fns/locale';
import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';
export default function GuidesPage() {
const [guides, setGuides] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [myLikes, setMyLikes] = useState<Set<string>>(new Set());
const { user } = useAuth();
const navigate = useNavigate();
useEffect(() => {
load();
}, []);
const load = async () => {
try {
const [data, likes] = await Promise.all([
api.getPublicGuides(50),
user ? api.getMyLikes() : Promise.resolve([]),
]);
setGuides(data);
setMyLikes(new Set(likes));
} catch (err) {
console.error('Rehberler yüklenemedi:', err);
} finally {
setLoading(false);
}
};
const handleLike = async (e: React.MouseEvent, guideId: string) => {
e.preventDefault();
if (!user) { navigate('/login'); return; }
const wasLiked = myLikes.has(guideId);
setMyLikes(prev => {
const next = new Set(prev);
wasLiked ? next.delete(guideId) : next.add(guideId);
return next;
});
setGuides(prev => prev.map(g => g.id === guideId
? { ...g, likes_count: g.likes_count + (wasLiked ? -1 : 1) }
: g
));
try {
await api.toggleLike(guideId);
} catch {
setMyLikes(prev => {
const next = new Set(prev);
wasLiked ? next.add(guideId) : next.delete(guideId);
return next;
});
}
};
const getGuidePhoto = (guide: any) => {
const first = guide.itinerary?.days?.[0]?.items?.[0];
if (first?.photo_reference) {
return first.photo_reference.startsWith('http')
? first.photo_reference
: api.getPhotoUrl(first.photo_reference);
}
return 'https://images.unsplash.com/photo-1541167760496-1628856ab772?auto=format&fit=crop&q=80&w=800';
};
const getDayCount = (guide: any) => guide.itinerary?.days?.length || 0;
const getPlaceCount = (guide: any) =>
(guide.itinerary?.days || []).reduce((s: number, d: any) => s + (d.items?.length || 0), 0);
return (
<div className="min-h-screen bg-background">
{/* Hero */}
<div className="relative bg-secondary overflow-hidden">
<div className="absolute inset-0 opacity-20">
<img
src="https://images.unsplash.com/photo-1570168007204-dfb528c6958f?auto=format&fit=crop&q=80&w=2400"
className="w-full h-full object-cover"
alt=""
/>
</div>
<div className="absolute inset-0 bg-gradient-to-b from-secondary/80 to-secondary" />
<div className="relative max-w-5xl mx-auto px-6 pt-24 pb-16">
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
<div className="flex items-center gap-2 mb-4">
<Compass className="h-4 w-4 text-primary" />
<span className="text-[10px] font-black text-primary uppercase tracking-widest">Topluluk Rehberleri</span>
</div>
<h1 className="text-5xl md:text-6xl font-black text-white tracking-tighter uppercase leading-none mb-4">
REHBERLERİM
</h1>
<p className="text-white/50 text-lg font-medium italic max-w-md">
Gerçek gezginlerin oluşturduğu Kapadokya rotaları. Beğen, kopyala, yola çık.
</p>
</motion.div>
</div>
</div>
{/* Content */}
<div className="max-w-5xl mx-auto px-6 py-12">
{loading ? (
<div className="flex flex-col items-center justify-center py-24 gap-4">
<Loader2 className="h-10 w-10 animate-spin text-primary opacity-40" />
<p className="text-xs font-black text-gray-400 uppercase tracking-widest">Rehberler yükleniyor...</p>
</div>
) : guides.length === 0 ? (
<div className="text-center py-24 space-y-6">
<div className="w-20 h-20 bg-orange-50 rounded-3xl flex items-center justify-center mx-auto border-2 border-dashed border-orange-200">
<Compass className="h-8 w-8 text-orange-300" />
</div>
<div>
<h3 className="text-2xl font-black text-gray-900 tracking-tight uppercase">Henüz rehber yok</h3>
<p className="text-gray-400 text-sm mt-2 italic">İlk rehberi siz oluşturun.</p>
</div>
<Button className="bg-orange-600 hover:bg-orange-700 h-12 px-8 rounded-xl font-black" asChild>
<Link to="/planner">Rota Oluştur</Link>
</Button>
</div>
) : (
<>
<div className="flex items-center justify-between mb-8">
<p className="text-sm font-bold text-gray-400">{guides.length} rehber</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
{guides.map((guide, idx) => (
<motion.div
key={guide.id}
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: idx * 0.05 }}
>
<Link to={`/rehber/${guide.id}`} className="group block">
<div className="bg-white rounded-3xl overflow-hidden border-2 border-gray-50 shadow-sm hover:shadow-xl transition-all duration-300 hover:-translate-y-1">
<div className="relative h-52 overflow-hidden bg-gray-100">
<img
src={getGuidePhoto(guide)}
alt={guide.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
onError={(e) => {
(e.target as HTMLImageElement).src = 'https://images.unsplash.com/photo-1541167760496-1628856ab772?w=800&q=80';
}}
/>
<div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-transparent" />
<div className="absolute top-3 right-3 flex gap-1.5">
<Badge className="bg-black/40 text-white border-0 backdrop-blur-sm text-[9px] font-black px-2">
{getDayCount(guide)} GÜN
</Badge>
<Badge className="bg-black/40 text-white border-0 backdrop-blur-sm text-[9px] font-black px-2">
{getPlaceCount(guide)} DURAK
</Badge>
</div>
<button
onClick={(e) => handleLike(e, guide.id)}
className={cn(
'absolute top-3 left-3 w-9 h-9 rounded-full flex items-center justify-center backdrop-blur-sm transition-all',
myLikes.has(guide.id)
? 'bg-red-500 text-white'
: 'bg-black/30 text-white hover:bg-red-500'
)}
>
<Heart className={cn('h-4 w-4', myLikes.has(guide.id) && 'fill-current')} />
</button>
<div className="absolute bottom-3 left-4 right-4">
<h3 className="text-base font-black text-white leading-tight line-clamp-2 group-hover:text-orange-300 transition-colors">
{guide.title}
</h3>
</div>
</div>
<div className="p-4 space-y-3">
{guide.guide_intro && (
<p className="text-xs text-gray-500 italic leading-relaxed line-clamp-2">
"{guide.guide_intro}"
</p>
)}
<div className="flex items-center gap-4 text-[10px] font-bold text-gray-400">
<span className="flex items-center gap-1">
<MapPin className="h-3 w-3 text-primary" />
{guide.destination || 'Kapadokya'}
</span>
{guide.start_date && (
<span className="flex items-center gap-1">
<Calendar className="h-3 w-3 text-primary" />
{format(new Date(guide.start_date), 'd MMM yyyy', { locale: tr })}
</span>
)}
</div>
<div className="flex items-center justify-between pt-1 border-t border-gray-50">
<div className="flex items-center gap-3 text-[10px] font-bold text-gray-400">
<span className="flex items-center gap-1">
<Heart className="h-3 w-3" />
{guide.likes_count || 0}
</span>
<span className="flex items-center gap-1">
<Eye className="h-3 w-3" />
{guide.views_count || 0}
</span>
</div>
<span className="flex items-center gap-1 text-[10px] font-black text-orange-600 group-hover:gap-2 transition-all">
İncele <ArrowRight className="h-3 w-3" />
</span>
</div>
</div>
</div>
</Link>
</motion.div>
))}
</div>
</>
)}
</div>
</div>
);
}

View File

@ -155,7 +155,7 @@ const PlannerPage = () => {
try { try {
const startDate = format(data.dateRange.from, 'yyyy-MM-dd'); const startDate = format(data.dateRange.from, 'yyyy-MM-dd');
const endDate = format(data.dateRange.to, 'yyyy-MM-dd'); const endDate = format(data.dateRange.to, 'yyyy-MM-dd');
const result = await retryWithBackoff( const result: any = await retryWithBackoff(
() => withTimeout( () => withTimeout(
api.generateItinerary({ api.generateItinerary({
startDate, startDate,
@ -174,6 +174,16 @@ const PlannerPage = () => {
{ maxRetries: 2, initialDelay: 1000, maxDelay: 5000 } { maxRetries: 2, initialDelay: 1000, maxDelay: 5000 }
); );
clearInterval(iv); clearInterval(iv);
// Kullanıcıya AI/mock durumunu bildir
if (!result.ai_used) {
toast.warning('Demo rota oluşturuldu', {
description: result.ai_error ?? 'AI kullanılamadı, örnek rota gösteriliyor.',
duration: 10000,
});
}
const itinerary = { days: result.days };
if (user) { if (user) {
const saved = await api.saveTrip({ const saved = await api.saveTrip({
user_id: user.id, user_id: user.id,
@ -191,12 +201,12 @@ const PlannerPage = () => {
budget: data.budget, budget: data.budget,
travelers: data.travelers, travelers: data.travelers,
}, },
itinerary: result, itinerary,
}); });
navigate(`/trip/${saved.id}`); navigate(`/trip/${saved.id}`);
toast.success('Rotanız hazır!'); toast.success('Rotanız hazır!');
} else { } else {
sessionStorage.setItem('pending_trip', JSON.stringify(result)); sessionStorage.setItem('pending_trip', JSON.stringify(itinerary));
navigate('/login', { state: { from: '/planner', message: 'Planınızı kaydetmek için giriş yapın' } }); navigate('/login', { state: { from: '/planner', message: 'Planınızı kaydetmek için giriş yapın' } });
} }
} catch (err) { } catch (err) {

View File

@ -1,12 +1,12 @@
import { useEffect, useState, useCallback, useMemo, useRef } from 'react'; import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate, Link } from 'react-router-dom';
import api, { Trip, Place, ItineraryDay } from '@/db/api'; import api, { Trip, Place, ItineraryDay } from '@/db/api';
import { Timeline } from '@/components/trip/Timeline'; import { Timeline } from '@/components/trip/Timeline';
import { TripMap } from '@/components/trip/Map'; import { TripMap } from '@/components/trip/Map';
import { import {
Loader2, Share2, MapPin, Trash2, Zap, Loader2, Share2, MapPin, Trash2,
Plus, Sparkles, LayoutGrid, RotateCcw, RotateCw, Plus, LayoutGrid, RotateCcw, RotateCw,
CheckCircle2, Clock, Navigation CheckCircle2, Clock, Navigation, Globe, GlobeLock, X
} from 'lucide-react'; } from 'lucide-react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@ -67,6 +67,13 @@ export default function TripDetailsPage() {
const [saveStatus, setSaveStatus] = useState<'saved' | 'saving' | 'unsaved'>('saved'); const [saveStatus, setSaveStatus] = useState<'saved' | 'saving' | 'unsaved'>('saved');
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null); const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Publish modal
const [showPublishModal, setShowPublishModal] = useState(false);
const [publishLoading, setPublishLoading] = useState(false);
const [guideIntro, setGuideIntro] = useState('');
const [guideTips, setGuideTips] = useState('');
const [isPublic, setIsPublic] = useState(false);
// History operates on the full itinerary object // History operates on the full itinerary object
const history = useUndoRedo<Trip['itinerary'] | null>(null); const history = useUndoRedo<Trip['itinerary'] | null>(null);
@ -79,6 +86,9 @@ export default function TripDetailsPage() {
if (data) { if (data) {
setTrip(data); setTrip(data);
history.push(data.itinerary); history.push(data.itinerary);
setIsPublic(!!(data as any).is_public);
setGuideIntro((data as any).guide_intro || '');
setGuideTips(((data as any).guide_tips || []).join('\n'));
} else { } else {
toast.error('Gezi bulunamadı'); toast.error('Gezi bulunamadı');
navigate('/explore'); navigate('/explore');
@ -226,6 +236,33 @@ export default function TripDetailsPage() {
} }
}; };
const handlePublish = async () => {
if (!trip) return;
setPublishLoading(true);
try {
const tips = guideTips.split('\n').map(t => t.trim()).filter(Boolean);
await api.publishGuide(trip.id, { guide_intro: guideIntro, guide_tips: tips });
setIsPublic(true);
setShowPublishModal(false);
toast.success('Rehber yayınlandı! Toplulukta görünüyor.');
} catch {
toast.error('Yayınlama başarısız');
} finally {
setPublishLoading(false);
}
};
const handleUnpublish = async () => {
if (!trip) return;
try {
await api.unpublishGuide(trip.id);
setIsPublic(false);
toast.success('Rehber yayından kaldırıldı');
} catch {
toast.error('İşlem başarısız');
}
};
const handleDelete = async () => { const handleDelete = async () => {
if (!trip) return; if (!trip) return;
try { try {
@ -279,6 +316,63 @@ export default function TripDetailsPage() {
return ( return (
<div className="flex flex-col h-[calc(100vh-64px)] overflow-hidden bg-background"> <div className="flex flex-col h-[calc(100vh-64px)] overflow-hidden bg-background">
{/* ── Publish Modal ────────────────────────────────────────────────── */}
{showPublishModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-md p-6 space-y-5">
<div className="flex items-center justify-between">
<div>
<h2 className="text-xl font-black text-gray-900 tracking-tight">Rehber Olarak Yayınla</h2>
<p className="text-xs text-gray-400 mt-0.5">Rotanız toplulukla paylaşılacak</p>
</div>
<button onClick={() => setShowPublishModal(false)}
className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center hover:bg-gray-200 transition-all">
<X className="h-4 w-4 text-gray-500" />
</button>
</div>
<div className="space-y-4">
<div>
<label className="text-xs font-black text-gray-700 uppercase tracking-wider block mb-1.5">
Kişisel Notunuz
</label>
<textarea
value={guideIntro}
onChange={e => setGuideIntro(e.target.value)}
placeholder="Kapadokya'ya kaç kez gittiğinizi, gezi deneyiminizi kısaca anlatın..."
rows={3}
className="w-full text-sm border border-gray-200 rounded-xl px-3 py-2.5 resize-none focus:outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-400"
/>
</div>
<div>
<label className="text-xs font-black text-gray-700 uppercase tracking-wider block mb-1.5">
Genel İpuçları <span className="text-gray-400 font-normal">(her satır ayrı ipucu)</span>
</label>
<textarea
value={guideTips}
onChange={e => setGuideTips(e.target.value)}
placeholder={"Sabah erken çıkın, turist kalabalığından kaçınırsınız\nBalon turu için 3 ay önceden rezervasyon yapın\nNevşehir'den araç kiralamak en pratik seçenek"}
rows={4}
className="w-full text-sm border border-gray-200 rounded-xl px-3 py-2.5 resize-none focus:outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-400"
/>
</div>
</div>
<div className="flex gap-3 pt-1">
<Button variant="outline" className="flex-1 h-11 rounded-xl font-bold"
onClick={() => setShowPublishModal(false)}>
Vazgeç
</Button>
<Button className="flex-1 h-11 rounded-xl font-black bg-orange-600 hover:bg-orange-700 gap-2"
onClick={handlePublish} disabled={publishLoading}>
{publishLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Globe className="h-4 w-4" />}
Yayınla
</Button>
</div>
</div>
</div>
)}
{/* ── Sub-header ──────────────────────────────────────────────────── */} {/* ── Sub-header ──────────────────────────────────────────────────── */}
<div className="h-14 border-b bg-white flex items-center px-4 gap-3 shrink-0 shadow-sm"> <div className="h-14 border-b bg-white flex items-center px-4 gap-3 shrink-0 shadow-sm">
@ -355,6 +449,24 @@ export default function TripDetailsPage() {
</Button> </Button>
)} )}
{user && (
isPublic ? (
<Button variant="outline" size="sm"
className="h-8 px-3 rounded-xl border-green-200 text-green-700 bg-green-50 hover:bg-red-50 hover:text-red-600 hover:border-red-200 text-xs font-bold gap-1.5 transition-all"
onClick={handleUnpublish}>
<Globe className="h-3.5 w-3.5" />
Yayında
</Button>
) : (
<Button variant="outline" size="sm"
className="h-8 px-3 rounded-xl border-orange-200 text-orange-700 bg-orange-50 hover:bg-orange-100 text-xs font-bold gap-1.5"
onClick={() => setShowPublishModal(true)}>
<GlobeLock className="h-3.5 w-3.5" />
Yayınla
</Button>
)
)}
<Button variant="ghost" size="icon" className="h-8 w-8 text-gray-500 hover:text-gray-900" onClick={handleShare}> <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-500 hover:text-gray-900" onClick={handleShare}>
<Share2 className="h-4 w-4" /> <Share2 className="h-4 w-4" />
</Button> </Button>
@ -380,17 +492,6 @@ export default function TripDetailsPage() {
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
<div className="h-4 w-px bg-gray-200 mx-0.5" />
<Button variant="outline" size="sm" className="h-8 px-3 rounded-xl border-gray-200 text-xs font-bold gap-1.5">
<Sparkles className="h-3.5 w-3.5 text-purple-500" />
AI Rota
</Button>
<Button variant="outline" size="sm" className="h-8 px-3 rounded-xl border-gray-200 text-xs font-bold gap-1.5">
<Zap className="h-3.5 w-3.5 text-blue-500" />
Optimize
</Button>
</div> </div>
</div> </div>
@ -464,10 +565,11 @@ export default function TripDetailsPage() {
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button variant="outline" size="sm" className="h-8 rounded-xl text-xs font-bold gap-1.5 border-gray-100"> <Button size="sm" className="h-8 rounded-xl text-xs font-bold gap-1.5 bg-orange-600 hover:bg-orange-700"
<Sparkles className="h-3 w-3 text-orange-500" />AI onClick={() => {
</Button> document.getElementById(`place-search-day-0`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
<Button size="sm" className="h-8 rounded-xl text-xs font-bold gap-1.5 bg-orange-600 hover:bg-orange-700"> setTimeout(() => (document.querySelector(`#place-search-day-0 input`) as HTMLInputElement)?.focus(), 400);
}}>
<Plus className="h-3 w-3" />Yer Ekle <Plus className="h-3 w-3" />Yer Ekle
</Button> </Button>
</div> </div>

View File

@ -4,6 +4,8 @@ import TripDetailsPage from './pages/TripDetailsPage';
import AccountPage from './pages/AccountPage'; import AccountPage from './pages/AccountPage';
import ExplorePage from './pages/ExplorePage'; import ExplorePage from './pages/ExplorePage';
import LoginPage from './pages/LoginPage'; import LoginPage from './pages/LoginPage';
import GuidesPage from './pages/GuidesPage';
import GuideDetailPage from './pages/GuideDetailPage';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
interface RouteConfig { interface RouteConfig {
@ -42,6 +44,16 @@ const routes: RouteConfig[] = [
name: 'Login', name: 'Login',
path: '/login', path: '/login',
element: <LoginPage /> element: <LoginPage />
},
{
name: 'Guides',
path: '/rehberler',
element: <GuidesPage />
},
{
name: 'Guide Detail',
path: '/rehber/:id',
element: <GuideDetailPage />
} }
]; ];

View File

@ -0,0 +1,58 @@
-- Add new columns to trips table
ALTER TABLE trips
ADD COLUMN IF NOT EXISTS is_public boolean DEFAULT false,
ADD COLUMN IF NOT EXISTS guide_intro text,
ADD COLUMN IF NOT EXISTS guide_tips text[],
ADD COLUMN IF NOT EXISTS views_count integer DEFAULT 0,
ADD COLUMN IF NOT EXISTS likes_count integer DEFAULT 0,
ADD COLUMN IF NOT EXISTS published_at timestamptz;
-- Create guide_likes table
CREATE TABLE IF NOT EXISTS guide_likes (
user_id uuid REFERENCES profiles(id) ON DELETE CASCADE,
trip_id uuid REFERENCES trips(id) ON DELETE CASCADE,
created_at timestamptz DEFAULT now(),
PRIMARY KEY (user_id, trip_id)
);
-- Enable RLS for guide_likes
ALTER TABLE guide_likes ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view guide likes" ON guide_likes FOR SELECT USING (true);
CREATE POLICY "Users can insert their own likes" ON guide_likes FOR INSERT WITH CHECK (auth.uid() = user_id);
CREATE POLICY "Users can delete their own likes" ON guide_likes FOR DELETE USING (auth.uid() = user_id);
-- Update RLS for trips
ALTER TABLE trips ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Public trips are viewable by everyone" ON trips FOR SELECT USING (is_public = true);
-- SQL Function to increment view count
CREATE OR REPLACE FUNCTION increment_guide_views(p_trip_id uuid)
RETURNS void AS $$
BEGIN
UPDATE trips
SET views_count = views_count + 1
WHERE id = p_trip_id AND is_public = true;
END;
$$ LANGUAGE plpgsql;
-- Trigger function to sync likes count
CREATE OR REPLACE FUNCTION update_trip_likes_count()
RETURNS TRIGGER AS $$
BEGIN
IF (TG_OP = 'INSERT') THEN
UPDATE trips SET likes_count = likes_count + 1 WHERE id = NEW.trip_id;
ELSIF (TG_OP = 'DELETE') THEN
UPDATE trips SET likes_count = likes_count - 1 WHERE id = OLD.trip_id;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_update_trip_likes_count
AFTER INSERT OR DELETE ON guide_likes
FOR EACH ROW EXECUTE FUNCTION update_trip_likes_count();
-- Create composite index
CREATE INDEX IF NOT EXISTS idx_public_trips_ranking ON trips (likes_count DESC, views_count DESC) WHERE is_public = true;