'use client';

import { useReducer, useRef, useState, useEffect } from 'react';
import { ArrowLeft, ArrowRight, X, Plus, Link as LinkIcon, Camera, ImagePlus, Loader2, MapPin } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { apiUrl } from '@/lib/api';
import LocationPicker from './LocationPicker';
import PeoplePicker from './PeoplePicker';
import ArchivePhotoPicker from './ArchivePhotoPicker';

// ── Types ─────────────────────────────────────────────────

interface Place {
    id: string;
    name: string;
    link: string;
}

interface PhotoItem {
    file?: File;
    archivePhotoId?: string;
    previewUrl: string;
}

interface WizardState {
    step: number;
    title: string;
    location: string;
    latitude: number | null;
    longitude: number | null;
    startDate: string;
    endDate: string;
    people: string[];
    story: string;
    places: Place[];
    photos: PhotoItem[];
    direction: number; // 1 = forward, -1 = back
}

type WizardAction =
    | { type: 'SET_STEP'; step: number; direction: number }
    | { type: 'SET_TITLE'; value: string }
    | { type: 'SET_LOCATION'; value: string; latitude?: number | null; longitude?: number | null }
    | { type: 'SET_START_DATE'; value: string }
    | { type: 'SET_END_DATE'; value: string }
    | { type: 'SET_PEOPLE'; value: string[] }
    | { type: 'SET_STORY'; value: string }
    | { type: 'ADD_PLACE' }
    | { type: 'UPDATE_PLACE'; id: string; field: 'name' | 'link'; value: string }
    | { type: 'REMOVE_PLACE'; id: string }
    | { type: 'ADD_PHOTOS'; items: PhotoItem[] }
    | { type: 'REMOVE_PHOTO'; index: number };

const TOTAL_STEPS = 8;

function reducer(state: WizardState, action: WizardAction): WizardState {
    switch (action.type) {
        case 'SET_STEP':
            return { ...state, step: action.step, direction: action.direction };
        case 'SET_TITLE':
            return { ...state, title: action.value };
        case 'SET_LOCATION':
            return {
                ...state,
                location: action.value,
                latitude: action.latitude ?? state.latitude,
                longitude: action.longitude ?? state.longitude,
            };
        case 'SET_START_DATE':
            return { ...state, startDate: action.value };
        case 'SET_END_DATE':
            return { ...state, endDate: action.value };
        case 'SET_PEOPLE':
            return { ...state, people: action.value };
        case 'SET_STORY':
            return { ...state, story: action.value };
        case 'ADD_PLACE':
            return { ...state, places: [...state.places, { id: crypto.randomUUID(), name: '', link: '' }] };
        case 'UPDATE_PLACE':
            return {
                ...state,
                places: state.places.map(p =>
                    p.id === action.id ? { ...p, [action.field]: action.value } : p
                ),
            };
        case 'REMOVE_PLACE':
            return { ...state, places: state.places.filter(p => p.id !== action.id) };
        case 'ADD_PHOTOS':
            return { ...state, photos: [...state.photos, ...action.items] };
        case 'REMOVE_PHOTO': {
            const removed = state.photos[action.index];
            if (removed?.file) URL.revokeObjectURL(removed.previewUrl);
            return { ...state, photos: state.photos.filter((_, i) => i !== action.index) };
        }
        default:
            return state;
    }
}

const initialState: WizardState = {
    step: 1,
    title: '',
    location: '',
    latitude: null,
    longitude: null,
    startDate: '',
    endDate: '',
    people: [],
    story: '',
    places: [],
    photos: [],
    direction: 1,
};

// ── Wizard Component ──────────────────────────────────────

interface JourneyWizardProps {
    onComplete: (journey: { id: string }) => void;
    onCancel: () => void;
}

export default function JourneyWizard({ onComplete, onCancel }: JourneyWizardProps) {
    const [state, dispatch] = useReducer(reducer, initialState);
    const [submitting, setSubmitting] = useState(false);
    const [availablePeople, setAvailablePeople] = useState<string[]>([]);
    const [showArchivePicker, setShowArchivePicker] = useState(false);
    const fileRef = useRef<HTMLInputElement>(null);

    // Lock body scroll while wizard is open
    useEffect(() => {
        document.body.style.overflow = 'hidden';
        return () => { document.body.style.overflow = ''; };
    }, []);

    // Fetch available people for the PeoplePicker
    useEffect(() => {
        fetch(apiUrl('/api/feed/metadata'))
            .then(res => res.json())
            .then(data => { if (data.people) setAvailablePeople(data.people); })
            .catch(() => {});
    }, []);

    const { step, direction } = state;

    const canGoNext = step === 1 ? state.title.trim().length > 0 : true;

    const goTo = (target: number) => {
        if (target < 1 || target > TOTAL_STEPS) return;
        dispatch({ type: 'SET_STEP', step: target, direction: target > step ? 1 : -1 });
    };

    const handleNext = () => {
        if (step < TOTAL_STEPS) goTo(step + 1);
    };
    const handleBack = () => {
        if (step > 1) goTo(step - 1);
    };
    const handleSkip = () => {
        if (step < TOTAL_STEPS) goTo(step + 1);
    };

    // ── File handling ──
    const handleFileSelect = (files: FileList) => {
        const items: PhotoItem[] = Array.from(files).map(file => ({
            file,
            previewUrl: URL.createObjectURL(file),
        }));
        dispatch({ type: 'ADD_PHOTOS', items });
    };

    const handleArchiveSelect = (photoIds: string[]) => {
        setShowArchivePicker(false);
        // We need the photo URLs — fetch them
        Promise.all(
            photoIds.map(id =>
                fetch(apiUrl(`/api/photos/${id}`))
                    .then(r => r.json())
                    .then(photo => ({
                        archivePhotoId: photo.id,
                        previewUrl: photo.url,
                    } as PhotoItem))
            )
        ).then(items => {
            dispatch({ type: 'ADD_PHOTOS', items });
        }).catch(console.error);
    };

    // ── Submit ──
    const handleSubmit = async () => {
        if (submitting) return;
        setSubmitting(true);

        try {
            // 1. Create journey
            const peopleStr = state.people.length > 0
                ? `Com ${state.people.join(', ')}.`
                : '';
            const description = peopleStr || null;

            const journeyRes = await fetch(apiUrl('/api/journeys'), {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    title: state.title.trim(),
                    description,
                    startDate: state.startDate || null,
                    endDate: state.endDate || null,
                }),
            });

            if (!journeyRes.ok) throw new Error('Failed to create journey');
            const journey = await journeyRes.json();
            const journeyId = journey.id;

            let order = 0;

            // 2. Text block (story)
            if (state.story.trim()) {
                await fetch(apiUrl(`/api/journeys/${journeyId}/blocks`), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ type: 'text', text: state.story.trim(), order }),
                });
                order++;
            }

            // 3. Main location block
            if (state.location) {
                await fetch(apiUrl(`/api/journeys/${journeyId}/blocks`), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        type: 'location',
                        locationName: state.location,
                        latitude: state.latitude,
                        longitude: state.longitude,
                        order,
                    }),
                });
                order++;
            }

            // 4. Photos — upload files + create gallery from archive photos
            const archivePhotoIds = state.photos
                .filter(p => p.archivePhotoId)
                .map(p => p.archivePhotoId!);
            const filePhotos = state.photos.filter(p => p.file);

            // Upload file photos individually as image blocks
            for (const photo of filePhotos) {
                const formData = new FormData();
                formData.append('file', photo.file!);
                formData.append('order', String(order));
                await fetch(apiUrl(`/api/journeys/${journeyId}/blocks`), {
                    method: 'POST',
                    body: formData,
                });
                order++;
            }

            // Archive photos as gallery block
            if (archivePhotoIds.length === 1) {
                await fetch(apiUrl(`/api/journeys/${journeyId}/blocks`), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ type: 'image', photoId: archivePhotoIds[0], order }),
                });
                order++;
            } else if (archivePhotoIds.length > 1) {
                await fetch(apiUrl(`/api/journeys/${journeyId}/blocks`), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ type: 'gallery', photoIds: archivePhotoIds, order }),
                });
                order++;
            }

            // 5. Visited places as location blocks
            for (const place of state.places) {
                if (!place.name.trim()) continue;
                await fetch(apiUrl(`/api/journeys/${journeyId}/blocks`), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        type: 'location',
                        locationName: place.name.trim(),
                        text: place.link.trim() || null,
                        order,
                    }),
                });
                order++;
            }

            // 6. Auto-set cover from first uploaded photo (API does it automatically)

            onComplete({ id: journeyId });
        } catch (error) {
            console.error('Wizard submit error:', error);
            alert('Algo deu errado. Tente novamente.');
        } finally {
            setSubmitting(false);
        }
    };

    // ── Step content ──
    const slideVariants = {
        enter: (d: number) => ({ x: d > 0 ? '30%' : '-30%', opacity: 0 }),
        center: { x: 0, opacity: 1 },
        exit: (d: number) => ({ x: d < 0 ? '30%' : '-30%', opacity: 0 }),
    };

    const isSkippable = step >= 2 && step <= 7;

    return (
        <div className="fixed top-0 left-0 right-0 bottom-0 z-50 bg-paper flex flex-col" style={{ height: '100vh', height: '100dvh' } as React.CSSProperties}>
            {/* Header */}
            <div className="shrink-0 flex items-center justify-between px-4 pt-4 pb-2">
                <button
                    onClick={step === 1 ? onCancel : handleBack}
                    className="p-2 -ml-2 rounded-lg text-foreground/40 hover:text-foreground transition-colors"
                >
                    {step === 1 ? <X className="w-6 h-6" /> : <ArrowLeft className="w-6 h-6" />}
                </button>

                {/* Progress dots */}
                <div className="flex items-center gap-1.5">
                    {Array.from({ length: TOTAL_STEPS }, (_, i) => (
                        <div
                            key={i}
                            className={`h-1.5 rounded-full transition-all duration-300 ${
                                i + 1 === step
                                    ? 'bg-[#8B7355] w-5'
                                    : i + 1 < step
                                    ? 'bg-[#8B7355]/40 w-1.5'
                                    : 'bg-foreground/10 w-1.5'
                            }`}
                        />
                    ))}
                </div>

                <button
                    onClick={onCancel}
                    className="p-2 -mr-2 rounded-lg text-foreground/40 hover:text-foreground transition-colors"
                >
                    <X className="w-6 h-6" />
                </button>
            </div>

            {/* Content */}
            <div className="flex-1 min-h-0 overflow-y-auto px-6 py-8">
                <AnimatePresence initial={false} custom={direction} mode="wait">
                    <motion.div
                        key={step}
                        custom={direction}
                        variants={slideVariants}
                        initial="enter"
                        animate="center"
                        exit="exit"
                        transition={{ duration: 0.3, ease: [0.25, 1, 0.5, 1] }}
                        className="w-full max-w-lg mx-auto"
                    >
                        {step === 1 && <StepTitle state={state} dispatch={dispatch} />}
                        {step === 2 && <StepLocation state={state} dispatch={dispatch} />}
                        {step === 3 && <StepDates state={state} dispatch={dispatch} />}
                        {step === 4 && (
                            <StepPeople
                                state={state}
                                dispatch={dispatch}
                                availablePeople={availablePeople}
                            />
                        )}
                        {step === 5 && <StepStory state={state} dispatch={dispatch} />}
                        {step === 6 && <StepPlaces state={state} dispatch={dispatch} />}
                        {step === 7 && (
                            <StepPhotos
                                state={state}
                                dispatch={dispatch}
                                fileRef={fileRef}
                                onShowArchive={() => setShowArchivePicker(true)}
                            />
                        )}
                        {step === 8 && <StepPreview state={state} />}
                    </motion.div>
                </AnimatePresence>
            </div>

            {/* Footer */}
            <div className="shrink-0 px-6 pb-6 pt-3">
                <div className="flex items-center gap-3 max-w-lg mx-auto">
                    {isSkippable && (
                        <button
                            onClick={handleSkip}
                            className="px-5 py-3 rounded-xl text-base font-serif text-foreground/35 hover:text-foreground/60 transition-colors"
                        >
                            Pular
                        </button>
                    )}
                    <div className="flex-1" />
                    {step < TOTAL_STEPS ? (
                        <button
                            onClick={handleNext}
                            disabled={!canGoNext}
                            className="flex items-center gap-2 px-6 py-3 rounded-xl text-base font-medium
                                       bg-foreground text-paper hover:bg-foreground/90 transition-colors
                                       disabled:opacity-30 disabled:cursor-not-allowed min-h-[48px]"
                        >
                            Próximo
                            <ArrowRight className="w-5 h-5" />
                        </button>
                    ) : (
                        <button
                            onClick={handleSubmit}
                            disabled={submitting}
                            className="flex items-center gap-2 px-8 py-3 rounded-xl text-base font-medium
                                       bg-[#8B7355] text-paper hover:bg-[#7a6348] transition-colors
                                       disabled:opacity-50 min-h-[48px]"
                        >
                            {submitting ? (
                                <>
                                    <Loader2 className="w-5 h-5 animate-spin" />
                                    Criando...
                                </>
                            ) : (
                                'Criar História'
                            )}
                        </button>
                    )}
                </div>
            </div>

            {/* Hidden file input */}
            <input
                ref={fileRef}
                type="file"
                accept="image/*"
                multiple
                className="hidden"
                onChange={e => {
                    if (e.target.files) handleFileSelect(e.target.files);
                    e.target.value = '';
                }}
            />

            {/* Archive photo picker */}
            {showArchivePicker && (
                <ArchivePhotoPicker
                    onSelect={handleArchiveSelect}
                    onClose={() => setShowArchivePicker(false)}
                />
            )}
        </div>
    );
}


// ── Step Components ───────────────────────────────────────

function StepTitle({ state, dispatch }: { state: WizardState; dispatch: React.Dispatch<WizardAction> }) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                Sobre o que é essa história?
            </h2>
            <input
                type="text"
                value={state.title}
                onChange={e => dispatch({ type: 'SET_TITLE', value: e.target.value })}
                placeholder="Ex: Férias em Portugal..."
                autoFocus
                className="w-full text-lg font-serif bg-transparent border-b-2 border-foreground/15
                           focus:border-[#8B7355] py-3 focus:outline-none placeholder:text-foreground/20
                           transition-colors"
            />
        </div>
    );
}

function StepLocation({ state, dispatch }: { state: WizardState; dispatch: React.Dispatch<WizardAction> }) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                Onde foi isso?
            </h2>
            <LocationPicker
                value={state.location}
                onChange={val => dispatch({ type: 'SET_LOCATION', value: val })}
                onSelectWithCoords={({ name, latitude, longitude }) =>
                    dispatch({ type: 'SET_LOCATION', value: name, latitude, longitude })
                }
                placeholder="Ex: Lisboa, Portugal..."
                className="text-lg"
            />
        </div>
    );
}

function StepDates({ state, dispatch }: { state: WizardState; dispatch: React.Dispatch<WizardAction> }) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                Quando foi?
            </h2>
            <div className="space-y-4">
                <div>
                    <label className="block text-sm font-serif text-foreground/40 mb-1.5">Início</label>
                    <input
                        type="date"
                        value={state.startDate}
                        onChange={e => dispatch({ type: 'SET_START_DATE', value: e.target.value })}
                        className="w-full text-lg font-serif bg-transparent border-b-2 border-foreground/15
                                   focus:border-[#8B7355] py-3 focus:outline-none transition-colors"
                    />
                </div>
                <div>
                    <label className="block text-sm font-serif text-foreground/40 mb-1.5">Fim</label>
                    <input
                        type="date"
                        value={state.endDate}
                        onChange={e => dispatch({ type: 'SET_END_DATE', value: e.target.value })}
                        className="w-full text-lg font-serif bg-transparent border-b-2 border-foreground/15
                                   focus:border-[#8B7355] py-3 focus:outline-none transition-colors"
                    />
                </div>
            </div>
        </div>
    );
}

function StepPeople({
    state,
    dispatch,
    availablePeople,
}: {
    state: WizardState;
    dispatch: React.Dispatch<WizardAction>;
    availablePeople: string[];
}) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                Quem estava lá?
            </h2>
            <PeoplePicker
                value={state.people}
                onChange={people => dispatch({ type: 'SET_PEOPLE', value: people })}
                availablePeople={availablePeople}
                placeholder="Ex: Ana, Bruno..."
                className="text-lg"
            />
        </div>
    );
}

function StepStory({ state, dispatch }: { state: WizardState; dispatch: React.Dispatch<WizardAction> }) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                O que você lembra?
            </h2>
            <textarea
                value={state.story}
                onChange={e => dispatch({ type: 'SET_STORY', value: e.target.value })}
                placeholder="Conte um pouco dessa história..."
                rows={6}
                autoFocus
                className="w-full text-lg font-serif bg-transparent border-2 border-foreground/10
                           focus:border-[#8B7355]/40 rounded-xl py-3 px-4 focus:outline-none
                           placeholder:text-foreground/20 resize-none transition-colors leading-relaxed"
            />
        </div>
    );
}

function StepPlaces({ state, dispatch }: { state: WizardState; dispatch: React.Dispatch<WizardAction> }) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                Lugares que visitou?
            </h2>
            <p className="text-sm font-serif text-foreground/35 -mt-2">
                Restaurantes, cafés, pontos turísticos...
            </p>

            <div className="space-y-3">
                {state.places.map(place => (
                    <div key={place.id} className="flex items-start gap-2 bg-foreground/3 rounded-xl p-3">
                        <MapPin className="w-5 h-5 text-[#8B7355] mt-2.5 flex-shrink-0" />
                        <div className="flex-1 space-y-2">
                            <input
                                type="text"
                                value={place.name}
                                onChange={e => dispatch({ type: 'UPDATE_PLACE', id: place.id, field: 'name', value: e.target.value })}
                                placeholder="Nome do lugar"
                                className="w-full text-base font-serif bg-transparent border-b border-foreground/10
                                           focus:border-[#8B7355] py-1 focus:outline-none placeholder:text-foreground/20"
                            />
                            <div className="flex items-center gap-2">
                                <LinkIcon className="w-3.5 h-3.5 text-foreground/25 flex-shrink-0" />
                                <input
                                    type="url"
                                    value={place.link}
                                    onChange={e => dispatch({ type: 'UPDATE_PLACE', id: place.id, field: 'link', value: e.target.value })}
                                    placeholder="Link (opcional)"
                                    className="w-full text-sm font-serif bg-transparent border-b border-foreground/5
                                               focus:border-[#8B7355]/50 py-1 focus:outline-none placeholder:text-foreground/15"
                                />
                            </div>
                        </div>
                        <button
                            onClick={() => dispatch({ type: 'REMOVE_PLACE', id: place.id })}
                            className="p-1.5 rounded-full text-foreground/20 hover:text-red-400 transition-colors mt-1"
                        >
                            <X className="w-4 h-4" />
                        </button>
                    </div>
                ))}

                <button
                    onClick={() => dispatch({ type: 'ADD_PLACE' })}
                    className="flex items-center gap-2 w-full py-3 rounded-xl border-2 border-dashed border-foreground/10
                               text-foreground/35 hover:border-foreground/20 hover:text-foreground/50 transition-colors
                               justify-center text-base font-serif min-h-[48px]"
                >
                    <Plus className="w-5 h-5" />
                    Adicionar lugar
                </button>
            </div>
        </div>
    );
}

function StepPhotos({
    state,
    dispatch,
    fileRef,
    onShowArchive,
}: {
    state: WizardState;
    dispatch: React.Dispatch<WizardAction>;
    fileRef: React.RefObject<HTMLInputElement | null>;
    onShowArchive: () => void;
}) {
    return (
        <div className="space-y-6">
            <h2 className="font-display text-2xl text-foreground/80">
                Tem fotos?
            </h2>

            {/* Photo previews */}
            {state.photos.length > 0 && (
                <div className="grid grid-cols-3 gap-2">
                    {state.photos.map((photo, i) => (
                        <div key={i} className="relative aspect-square rounded-lg overflow-hidden group">
                            <img
                                src={photo.file ? photo.previewUrl : apiUrl(`/api/thumbnail/${photo.previewUrl.replace(/^\//, '')}?size=sm`)}
                                alt=""
                                className="w-full h-full object-cover"
                            />
                            <button
                                onClick={() => dispatch({ type: 'REMOVE_PHOTO', index: i })}
                                className="absolute top-1 right-1 w-6 h-6 bg-black/60 rounded-full
                                           flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                            >
                                <X className="w-3.5 h-3.5 text-white" />
                            </button>
                        </div>
                    ))}
                </div>
            )}

            {/* Upload buttons */}
            <div className="space-y-3">
                <button
                    onClick={() => fileRef.current?.click()}
                    className="flex items-center gap-3 w-full py-4 rounded-xl border-2 border-dashed border-foreground/10
                               text-foreground/40 hover:border-foreground/20 hover:text-foreground/60 transition-colors
                               justify-center text-base font-serif min-h-[56px]"
                >
                    <Camera className="w-5 h-5" />
                    Enviar do celular
                </button>
                <button
                    onClick={onShowArchive}
                    className="flex items-center gap-3 w-full py-4 rounded-xl border-2 border-dashed border-foreground/10
                               text-foreground/40 hover:border-foreground/20 hover:text-foreground/60 transition-colors
                               justify-center text-base font-serif min-h-[56px]"
                >
                    <ImagePlus className="w-5 h-5" />
                    Escolher do arquivo
                </button>
            </div>
        </div>
    );
}

function StepPreview({ state }: { state: WizardState }) {
    return (
        <div className="space-y-5 max-h-[60vh] overflow-y-auto -mx-2 px-2">
            <h2 className="font-display text-2xl text-foreground/80">
                Sua história ficou assim
            </h2>

            {/* Title */}
            <div>
                <h3 className="font-display text-xl">{state.title}</h3>
                {state.people.length > 0 && (
                    <p className="text-sm font-serif text-foreground/40 mt-1">
                        Com {state.people.join(', ')}
                    </p>
                )}
            </div>

            {/* Dates */}
            {(state.startDate || state.endDate) && (
                <p className="text-sm text-foreground/40 font-serif">
                    {state.startDate && new Date(state.startDate + 'T12:00:00').toLocaleDateString('pt-BR', { day: 'numeric', month: 'long', year: 'numeric' })}
                    {state.startDate && state.endDate && ' — '}
                    {state.endDate && new Date(state.endDate + 'T12:00:00').toLocaleDateString('pt-BR', { day: 'numeric', month: 'long', year: 'numeric' })}
                </p>
            )}

            {/* Location */}
            {state.location && (
                <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-full bg-[#8B7355] text-paper flex items-center justify-center">
                        <MapPin className="w-3 h-3" />
                    </div>
                    <span className="text-sm font-serif text-foreground/50">{state.location}</span>
                </div>
            )}

            {/* Story */}
            {state.story && (
                <p className="text-[15px] font-serif text-foreground/60 leading-relaxed">
                    {state.story}
                </p>
            )}

            {/* Photos preview */}
            {state.photos.length > 0 && (
                <div className="grid grid-cols-3 gap-1.5">
                    {state.photos.slice(0, 6).map((photo, i) => (
                        <div key={i} className="aspect-square rounded-lg overflow-hidden">
                            <img
                                src={photo.file ? photo.previewUrl : apiUrl(`/api/thumbnail/${photo.previewUrl.replace(/^\//, '')}?size=sm`)}
                                alt=""
                                className="w-full h-full object-cover"
                            />
                        </div>
                    ))}
                    {state.photos.length > 6 && (
                        <div className="aspect-square rounded-lg bg-foreground/5 flex items-center justify-center">
                            <span className="text-sm text-foreground/30 font-serif">+{state.photos.length - 6}</span>
                        </div>
                    )}
                </div>
            )}

            {/* Places */}
            {state.places.filter(p => p.name.trim()).length > 0 && (
                <div className="space-y-2">
                    <p className="text-xs text-foreground/30 uppercase tracking-wide font-medium">Lugares</p>
                    {state.places.filter(p => p.name.trim()).map(place => (
                        <div key={place.id} className="flex items-center gap-2">
                            <MapPin className="w-4 h-4 text-[#8B7355]" />
                            <span className="text-sm font-serif text-foreground/50">{place.name}</span>
                            {place.link && <LinkIcon className="w-3 h-3 text-foreground/20" />}
                        </div>
                    ))}
                </div>
            )}

            {/* Empty state warning */}
            {!state.story && state.photos.length === 0 && !state.location && state.places.length === 0 && (
                <p className="text-sm font-serif text-foreground/25 italic text-center py-4">
                    Apenas o título será criado. Você pode adicionar mais detalhes depois.
                </p>
            )}
        </div>
    );
}
