import { LocateFixed, PencilLine, RotateCcw, Search } from 'lucide-react';
import { useId, type ReactNode } from 'react';
import { offersGoogleRetry } from '../../utils/placeSource';
import { safeHexColor } from '../../utils/safeColor';
import { formatDistance } from '../../utils/units';
import CollectionPicker from '../Collections/CollectionPicker';
import ServiceStopSection from '../Roadtrip/ServiceStopSection';
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
fs,
} from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
import { getCategoryIcon } from '../shared/categoryIcons';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { EditorField, GRID_2, INPUT, LABEL, PANEL, TEXTAREA } from '../shared/dialogParts';
import { BookingCostsSection } from './BookingCostsSection';
import { PlaceContactFields } from './PlaceContactFields';
import PlaceDetailsColumn from './PlaceDetailsColumn';
import { HeaderPills } from './PlaceFormHeaderPills';
import { PlaceFormLocation } from './PlaceFormLocation';
import { PendingFiles, PlaceImageSection } from './PlaceFormMedia';
import { PlaceFormTags } from './PlaceFormTags';
import { PlaceFormTexts } from './PlaceFormTexts';
import { TimeSection } from './PlaceFormTimeSection';
import { PlaceRefreshPill } from './PlaceRefreshPill';
import { weekFromPeriods } from './placeHours';
import { SoftPill, tintOf } from './planParts';
import { usePlaceFormModal, type PlaceFormModalProps } from './usePlaceFormModal';
export type { PlaceSubmitData } from './usePlaceFormModal';
/** The mark itself. Quiet on purpose: it answers a question, it does not advertise. */
function SourceBadge({ label }: { label: string | null }) {
if (!label) return null;
return {label};
}
const ROW = 'flex items-stretch gap-5';
const STACK = 'flex flex-col gap-5';
const FORM_COLUMN = 'flex min-w-0 flex-1 flex-col gap-4';
/** A row of the typed-ahead list or of the search results. */
const PICK_ROW = 'flex w-full items-center gap-2 rounded-[8px] px-2.5 py-2 text-start';
/** The small accent square beside a field that runs its action, sized by the row it sits in. */
const SIDE_BUTTON =
'grid w-[38px] flex-none place-items-center rounded-[10px] transition-colors disabled:cursor-default disabled:opacity-60';
/**
* ServiceStopSection draws its labels in the old form's look and takes no class
* for them; this gives them the eyebrow every other field here has.
*/
const SERVICE_STOP_LABELS =
'[&_label]:mb-[5px] [&_label]:block [&_label]:font-geist [&_label]:text-[length:calc(9.5px*var(--fs-scale-caption,1))] [&_label]:font-bold [&_label]:uppercase [&_label]:tracking-[.08em] [&_label]:text-content-faint';
export default function PlaceFormModal(props: PlaceFormModalProps) {
const S = usePlaceFormModal(props);
const {
isOpen,
onClose,
place,
categories,
isMobile,
collectionsEnabled,
form,
isSearchingMaps,
t,
placesEnrichEnabled,
handleChange,
hasTimeError,
handleSubmit,
isSaving,
duplicateWarning,
serviceStop,
serviceStopDuplicate,
} = S;
const titleId = useId();
const fieldId = useId();
// Desktop + Collections addon → the saved-place picker on the right. Mobile
// always keeps the original single-column form untouched.
const proposal = props.proposal;
const assignmentOnly = proposal?.existing === true;
const twoColumn = !assignmentOnly && !isMobile && collectionsEnabled;
// The detail column sits on the left on desktop whenever enrichment is on; on
// mobile it stacks above the form. It stays mounted with the selection null
// rather than appearing on the first pick — otherwise the dialog would jump
// sideways mid-typing.
const showDetails = !assignmentOnly && placesEnrichEnabled;
const inRow = !isMobile && (showDetails || twoColumn);
// The form keeps about the same width whichever columns flank it: 552 px
// alone, 572 px beside one 320 px column, 552 px between two.
const width = inRow && showDetails && twoColumn ? 'xwide' : inRow ? 'wide' : 'detail';
// A stop on a drive is not an activity, and the title is the first thing that says
// which of the two this dialog is asking about. It is the band's eyebrow, and the
// place's own name is typed into the band under it, as on a booking.
const title =
place || proposal ? t('places.editPlace') : serviceStop ? t('roadtrip.stop.addTitle') : t('places.addPlace');
// The tile wears what the place is: the kind of stop on a drive, otherwise
// the chosen category, otherwise a plain pin.
const kind = serviceStop && form.stop_type ? STOP_KIND_BY_KEY[form.stop_type] : undefined;
const category = serviceStop ? undefined : (categories || []).find((c) => String(c.id) === form.category_id);
const tone = kind?.color ?? (category ? safeHexColor(category.color, '') : '');
const TileIcon = kind?.Icon ?? getCategoryIcon(category?.icon);
// The line under the name. A stop on a drive that looks like one already on the
// trip says so here, while the form is being filled, and never as a condition of
// saving: the press that saves is the press that saves. Otherwise, until there is
// a name, that one is required, since the save refuses without it.
let headerSub: ReactNode;
if (serviceStopDuplicate) {
headerSub = {t('roadtrip.stop.duplicate', { name: serviceStopDuplicate })};
} else if (!form.name.trim()) {
headerSub = `${t('places.formName')} *`;
}
const header = (
}
tint={tone ? tintOf(tone) : NEUTRAL_TINT}
labelId={titleId}
onClose={onClose}
eyebrow={title}
// Not autoFocused itself: a new place starts at the search, and otherwise the
// dialog's own first-field focus lands here on a desktop (#1302), so a place
// brought in from the map or opened to edit is ready for its name.
title={assignmentOnly ? form.name : undefined}
titleInput={
assignmentOnly
? undefined
: {
value: form.name,
onChange: (value) => handleChange('name', value),
label: `${t('places.formName')} *`,
placeholder: t('places.formNamePlaceholder'),
required: true,
}
}
sub={assignmentOnly ? form.address : headerSub}
subWraps={!!serviceStopDuplicate}
pills={
!assignmentOnly && (
handleChange('category_id', value)}
newCategory={
proposal
? undefined
: {
open: S.showNewCategory,
setOpen: S.setShowNewCategory,
name: S.newCategoryName,
setName: S.setNewCategoryName,
create: S.handleCreateCategory,
inputId: `${fieldId}-new-category`,
}
}
pickedSource={S.pickedSource}
refresh={}
busy={isSearchingMaps}
navPlace={
form.lat && form.lng
? {
name: form.name,
address: form.address,
lat: Number(form.lat),
lng: Number(form.lng),
google_place_id: form.google_place_id || null,
google_ftid: form.google_ftid || null,
}
: null
}
t={t}
/>
)
}
/>
);
const footer = (
{t('common.cancel')}
{/* The only way to save: Enter in a field never submits this form. */}
void handleSubmit()}
disabled={isSaving || hasTimeError || proposal?.disabled}
>
{isSaving
? t('common.saving')
: proposal
? t('common.save')
: place
? t('common.update')
: duplicateWarning
? t('places.addAnyway')
: t('common.add')}
);
const schedule = (proposal || (place && S.assignmentId)) && (
{showDetails && (
S.setDetailsHours(weekFromPeriods(hours.periods))}
hasDescription={!!form.description.trim()}
language={language}
timeFormat={S.timeFormat}
locale={S.locale}
variant="dialog"
// Stacked above the form in a narrow window, it takes the form's width.
fluid={isMobile}
t={t}
/>
)}
{twoColumn && }
{/* Autocomplete dropdown. Capped and scrolling, because plugin rows can
follow the core ones (#2221) and the list must stay inside the dialog;
the row the arrow keys land on is scrolled into view. */}
{acSuggestions.length > 0 && (
{acSuggestions.map((s, idx) => (
))}
)}
{/* Nothing found (#2472): say so, and offer the hand-made way in, taking
the query as the name when there is none yet. */}
{S.emptySearch && mapsResults.length === 0 && !isSearchingMaps && (
)}
{/* Search results (populated after full search) */}
{mapsResults.length > 0 && (
{mapsResults.map((result, idx) => (
))}
)}
{/* The index answers first and Google only when it finds nothing, so a
list with the wrong place on it never reaches Google by itself. One
quiet line under the list sends the same query there, on an instance
where Google holds the key slot and for a list Google did not
already produce. */}
{mapsResults.length > 0 && !nearbyList && offersGoogleRetry(searchSource, googleAnswers) && (
)}
{/* Phone, e-mail and the place's own hours, for what the search did not
know or a place nobody has listed (#2472). */}
handleChange(field, value, origin)}
/>