// PitStop UI Kit — Add / Edit flow (full-screen)
// The data-entry surface for the merged itinerary. A type picker → a focused
// full-screen form per item type. Recreated in the Dots language: mono kickers,
// heavy Manrope, hairline fields, pill save bar. Loaded before screens-trip.

const { useState: useStateAdd } = React;

// ── Canonical item-type registry — ONE lucide icon + colour token per type.
//    Shared by the timeline node, the agenda tick, the add menu and legends so
//    they never drift. Colours come from the --type-* tokens. ───────────────
const ITEM_TYPE = {
  stay:   { icon: 'bed',         color: 'var(--type-stay)',   label: 'Stay' },
  ride:   { icon: 'bike',        color: 'var(--type-ride)',   label: 'Ride' },
  walk:   { icon: 'footprints',  color: 'var(--type-walk)',   label: 'Walk' },
  drive:  { icon: 'car',         color: 'var(--type-drive)',  label: 'Drive' },
  // Travel (#572): any booked leg; the glyph follows the mode.
  travel: { icon: 'ticket',      color: 'var(--type-travel)', label: 'Travel' },
  flight: { icon: 'plane',       color: 'var(--type-travel)', label: 'Flight' },
  // Place (#572): any spot; the glyph follows the category.
  place:  { icon: 'map-pin',     color: 'var(--type-place)',  label: 'Place' },
  poi:    { icon: 'map-pin',     color: 'var(--type-place)',  label: 'Place' },
  food:   { icon: 'utensils',    color: 'var(--type-place)',  label: 'Food' },
  note:   { icon: 'sticky-note', color: 'var(--type-note)',   label: 'Note' },
};
// The five kinds offered when adding (#572); the route tile opens as a ride.
const ADD_ORDER = ['place', 'ride', 'travel', 'stay', 'note'];
const ADD_TILE = { ride: { icon: 'route', label: 'Route' } };

// ── Form primitives ───────────────────────────────────────────────────────
function FieldLabel({ children, hint }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.16em', color: 'hsl(var(--muted-ink))' }}>{children}</span>
      {hint && <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: '0.04em', color: 'hsl(var(--muted-ink) / 0.7)' }}>{hint}</span>}
    </div>
  );
}
function TextInput({ value, onChange, placeholder, icon, mono, big }) {
  const [focus, setFocus] = useStateAdd(false);
  return (
    <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
      {icon && <span style={{ position: 'absolute', left: 13, display: 'flex', color: 'hsl(var(--muted-ink))', pointerEvents: 'none' }}><Icon name={icon} size={18} /></span>}
      <input value={value} placeholder={placeholder} onChange={e => onChange && onChange(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{ width: '100%', height: big ? 52 : 46, padding: icon ? '0 14px 0 42px' : '0 14px',
          borderRadius: 'var(--radius-sm)', border: `1px solid ${focus ? 'hsl(var(--ember))' : 'hsl(var(--line-strong))'}`,
          background: 'hsl(var(--paper-raise))', color: 'hsl(var(--ink))', outline: 'none',
          fontFamily: mono ? 'var(--font-mono)' : 'var(--font-sans)', fontWeight: big ? 800 : 600,
          fontSize: big ? 20 : 15, letterSpacing: mono ? '0.02em' : 0,
          boxShadow: focus ? '0 0 0 3px var(--ember-soft)' : 'none', transition: 'border-color .15s, box-shadow .15s' }} />
    </div>
  );
}
function Field({ label, hint, children }) {
  return <div style={{ marginBottom: 16 }}><FieldLabel hint={hint}>{label}</FieldLabel>{children}</div>;
}
function TwoUp({ children }) { return <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>{children}</div>; }

function Segmented({ options, value, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 4, padding: 4, borderRadius: 'var(--radius-sm)', background: 'hsl(var(--paper-raise))', border: '1px solid hsl(var(--line-strong))' }}>
      {options.map(o => {
        const on = o.id === value;
        return (
          <button key={o.id} onClick={() => onChange(o.id)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, padding: '9px 0',
            border: 'none', borderRadius: 'var(--radius-sm)', cursor: 'pointer', transition: 'all .15s',
            background: on ? 'hsl(var(--ember))' : 'transparent', color: on ? '#fff' : 'hsl(var(--muted-ink))' }}>
            <Icon name={o.icon} size={18} color={on ? '#fff' : 'hsl(var(--muted-ink))'} />
            <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{o.label}</span>
          </button>
        );
      })}
    </div>
  );
}
function AttachRow({ icon, label, value, accent = 'ember' }) {
  return (
    <button style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', borderRadius: 'var(--radius-sm)',
      border: '1px solid hsl(var(--line-strong))', background: 'hsl(var(--paper-raise))', cursor: 'pointer', textAlign: 'left' }}>
      <Icon name={icon} size={19} color={`hsl(var(--${accent}))`} />
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14, color: 'hsl(var(--ink))' }}>{label}</span>
        {value && <span style={{ display: 'block', fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 11, color: 'hsl(var(--muted-ink))', marginTop: 2 }}>{value}</span>}
      </span>
      <Icon name="chevron-right" size={17} color="hsl(var(--muted-ink))" />
    </button>
  );
}
function MiniMap({ label = 'Pin on map' }) {
  return (
    <div style={{ position: 'relative', height: 116, borderRadius: 'var(--radius-md)', overflow: 'hidden', border: '1px solid hsl(var(--line))',
      background: 'linear-gradient(150deg, hsl(205 28% 30%), hsl(212 30% 22%))' }}>
      <div className="bg-dot-grid" style={{ position: 'absolute', inset: 0, opacity: 0.5 }} />
      <span style={{ position: 'absolute', left: '50%', top: '46%', transform: 'translate(-50%,-100%)', display: 'flex' }}>
        <Icon name="map-pin" size={28} color="hsl(var(--warm))" strokeWidth={2.4} />
      </span>
      <span style={{ position: 'absolute', left: 12, bottom: 10, fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'rgba(255,255,255,0.6)' }}>{label}</span>
    </div>
  );
}

// ── Full-screen chrome ─────────────────────────────────────────────────────
function FormShell({ kicker, title, accent, onClose, onSave, saveLabel, saveSub, children }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'hsl(var(--bg))', display: 'flex', flexDirection: 'column',
      animation: 'ps-sheet-up .26s cubic-bezier(.2,.8,.2,1)' }}>
      {/* header */}
      <div style={{ flexShrink: 0, padding: '54px 14px 14px', display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: '1px solid hsl(var(--line))', background: 'hsl(var(--bg) / 0.82)', backdropFilter: 'blur(12px)' }}>
        <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 999, border: 'none', cursor: 'pointer',
          background: 'hsl(var(--paper-raise))', color: 'hsl(var(--ink))', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="x" size={20} />
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          {kicker && <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.16em', color: accent ? 'hsl(var(--ember))' : 'hsl(var(--muted-ink))', marginBottom: 2 }}>{kicker}</div>}
          <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 19, letterSpacing: '-0.02em', color: 'hsl(var(--ink))' }}>{title}</div>
        </div>
      </div>
      {/* body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 16px 20px' }}>{children}</div>
      {/* save bar */}
      <div style={{ flexShrink: 0, padding: '12px 16px 26px', borderTop: '1px solid hsl(var(--line))', background: 'hsl(var(--bg) / 0.92)', backdropFilter: 'blur(12px)' }}>
        <Btn full size="lg" onClick={onSave}><Icon name="check" size={18} color="#fff" strokeWidth={2.4} /> {saveLabel}</Btn>
        {saveSub && <div style={{ textAlign: 'center', fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 10.5, letterSpacing: '0.04em', color: 'hsl(var(--muted-ink))', marginTop: 10 }}>{saveSub}</div>}
      </div>
    </div>
  );
}

// ── Type picker ────────────────────────────────────────────────────────────
function TypePicker({ dayLabel, onClose, onPick }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'hsl(var(--bg))', display: 'flex', flexDirection: 'column',
      animation: 'ps-sheet-up .26s cubic-bezier(.2,.8,.2,1)' }}>
      <div style={{ flexShrink: 0, padding: '54px 14px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid hsl(var(--line))' }}>
        <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 999, border: 'none', cursor: 'pointer',
          background: 'hsl(var(--paper-raise))', color: 'hsl(var(--ink))', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="x" size={20} />
        </button>
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.16em', color: 'hsl(var(--muted-ink))', marginBottom: 2 }}>{`Add to ${dayLabel}`}</div>
          <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 19, letterSpacing: '-0.02em', color: 'hsl(var(--ink))' }}>What are you adding?</div>
        </div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 16px 24px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {ADD_ORDER.map(k => {
            const t = { ...ITEM_TYPE[k], ...ADD_TILE[k] };
            return (
              <button key={k} onClick={() => onPick(k)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '16px 14px', borderRadius: 'var(--radius-md)',
                border: '1px solid hsl(var(--line))', background: 'hsl(var(--paper))', cursor: 'pointer', textAlign: 'left', boxShadow: 'var(--shadow-card)' }}>
                <span style={{ width: 44, height: 44, borderRadius: 999, background: `hsl(${t.color})`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Icon name={t.icon} size={21} color="#fff" />
                </span>
                <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 15.5, color: 'hsl(var(--ink))' }}>{t.label}</span>
              </button>
            );
          })}
        </div>
        <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 12, padding: '14px', borderRadius: 'var(--radius-md)', border: '1px dashed hsl(var(--line-strong))' }}>
          <Icon name="search" size={19} color="hsl(var(--muted-ink))" />
          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, color: 'hsl(var(--muted-ink))' }}>Search places, hotels &amp; flights…</span>
        </div>
      </div>
    </div>
  );
}

// ── Forms ──────────────────────────────────────────────────────────────────
function StayForm({ dayLabel, onClose, onSave }) {
  const [name, setName] = useStateAdd('Stazzo in Piazza, San Pantaleo');
  const [addr, setAddr] = useStateAdd('Piazza Pasquale Tola, Olbia');
  return (
    <FormShell kicker={`Stay · ${dayLabel}`} title="New stay" onClose={onClose}
      onSave={() => onSave({ type: 'stay', title: name, sub: addr, status: 'in', time: 'from 16:00' })}
      saveLabel="Save stay" saveSub="2 nights · checks out Sun 26 Apr">
      <Field label="Accommodation"><TextInput icon="bed" value={name} onChange={setName} /></Field>
      <Field label="Address"><TextInput icon="map-pin" value={addr} onChange={setAddr} /></Field>
      <div style={{ marginBottom: 16 }}><MiniMap /></div>
      <TwoUp>
        <Field label="Check-in"><TextInput icon="calendar-days" value="24 Apr" mono /></Field>
        <Field label="Time"><TextInput icon="clock" value="16:00" mono /></Field>
      </TwoUp>
      <TwoUp>
        <Field label="Check-out"><TextInput icon="calendar-days" value="26 Apr" mono /></Field>
        <Field label="Time"><TextInput icon="clock" value="10:00" mono /></Field>
      </TwoUp>
      <Field label="Booking"><AttachRow icon="link" label="Add confirmation or link" accent="warm" /></Field>
      <Field label="Notes"><TextInput value="" placeholder="Breakfast 8–10, bike storage in garage…" /></Field>
    </FormShell>
  );
}

function ActivityForm({ dayLabel, onClose, onSave }) {
  const [mode, setMode] = useStateAdd('ride');
  const [title, setTitle] = useStateAdd('Cala Gonone → Golfo Aranci');
  const [dist, setDist] = useStateAdd('58.5 km');
  const [dur, setDur] = useStateAdd('218 min');
  return (
    <FormShell kicker={`Activity · ${dayLabel}`} title="New activity" onClose={onClose}
      onSave={() => onSave({ type: mode, title, meta: `${dist} · ${dur}`, nav: true })}
      saveLabel="Save activity" saveSub={`adds ${dist} to ${dayLabel}`}>
      <Field label="Mode">
        <Segmented value={mode} onChange={setMode}
          options={[{ id: 'ride', icon: 'bike', label: 'Ride' }, { id: 'walk', icon: 'footprints', label: 'Walk' }, { id: 'drive', icon: 'car', label: 'Drive' }]} />
      </Field>
      <Field label="Title"><TextInput icon={ITEM_TYPE[mode].icon} value={title} onChange={setTitle} /></Field>
      <Field label="Start point"><TextInput icon="crosshair" value="Hotel Bue Marino" /></Field>
      <TwoUp>
        <Field label="Distance"><TextInput value={dist} onChange={setDist} mono /></Field>
        <Field label="Duration"><TextInput value={dur} onChange={setDur} mono /></Field>
      </TwoUp>
      <TwoUp>
        <Field label="Date"><TextInput icon="calendar-days" value="24 Apr" mono /></Field>
        <Field label="Start"><TextInput icon="clock" value="11:30" mono /></Field>
      </TwoUp>
      <Field label="Route"><AttachRow icon="navigation" label="Attach GPX route" value="golfo-aranci.gpx · 58.5 km" accent="ember" /></Field>
    </FormShell>
  );
}

function FlightForm({ dayLabel, onClose, onSave }) {
  const [from, setFrom] = useStateAdd('OLB');
  const [to, setTo] = useStateAdd('OSL');
  return (
    <FormShell kicker={`Travel · ${dayLabel}`} title="New flight" onClose={onClose}
      onSave={() => onSave({ type: 'flight', title: `${from} → ${to}`, meta: '3h 05m · 18:40' })}
      saveLabel="Save flight" saveSub="2 h 45 m · direct">
      <Field label="Airline & no."><TextInput icon="plane" value="SAS · SK4722" /></Field>
      <Field label="Route">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ flex: 1 }}><TextInput value={from} onChange={setFrom} mono big /></div>
          <button onClick={() => { setFrom(to); setTo(from); }} style={{ width: 38, height: 38, borderRadius: 999, flexShrink: 0, border: 'none', cursor: 'pointer',
            background: 'var(--ember-soft)', color: 'hsl(var(--ember))', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="arrow-left-right" size={18} />
          </button>
          <div style={{ flex: 1 }}><TextInput value={to} onChange={setTo} mono big /></div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 7, padding: '0 4px', fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 10.5, color: 'hsl(var(--muted-ink))' }}>
          <span>Olbia Costa Smeralda</span><span>Oslo Gardermoen</span>
        </div>
      </Field>
      <Field label="Date"><TextInput icon="calendar-days" value="26 Apr 2026" mono /></Field>
      <TwoUp>
        <Field label="Departs"><TextInput icon="clock" value="18:40" mono /></Field>
        <Field label="Arrives"><TextInput icon="clock" value="21:45" mono /></Field>
      </TwoUp>
      <TwoUp>
        <Field label="Terminal"><TextInput value="T1" mono /></Field>
        <Field label="Seat"><TextInput value="14C" mono /></Field>
      </TwoUp>
      <Field label="Confirmation"><AttachRow icon="link" label="Add booking reference" value="PNR · 7X9K2Q" accent="ember" /></Field>
    </FormShell>
  );
}

// Generic form — food / place / transfer / note share one simple shape.
function GenericForm({ type, dayLabel, onClose, onSave }) {
  const t = ITEM_TYPE[type];
  const cfg = {
    food: { titleLabel: 'Restaurant / spot', titleIcon: 'utensils', ph: 'Trattoria del Porto', save: 'Save food stop', sub: 'Booked for 4 · 20:30' },
    poi:  { titleLabel: 'Place name', titleIcon: 'map-pin', ph: 'Spiaggia di Cala Luna', save: 'Save place', sub: 'a stop worth making' },
    drive:{ titleLabel: 'Transfer', titleIcon: 'car', ph: 'Olbia Airport → Cala Gonone', save: 'Save transfer', sub: '64 km · 1h 10m' },
    note: { titleLabel: 'Note', titleIcon: 'sticky-note', ph: 'Pick up race numbers before 18:00', save: 'Save note', sub: '' },
  }[type] || { titleLabel: 'Title', titleIcon: t.icon, ph: '', save: 'Save', sub: '' };
  const [title, setTitle] = useStateAdd('');
  return (
    <FormShell kicker={`${t.label} · ${dayLabel}`} title={`New ${t.label.toLowerCase()}`} onClose={onClose}
      onSave={() => onSave({ type, title: title || cfg.ph, sub: type === 'note' ? undefined : cfg.sub, time: type === 'food' ? '20:30' : undefined })}
      saveLabel={cfg.save} saveSub={cfg.sub}>
      <Field label={cfg.titleLabel}><TextInput icon={cfg.titleIcon} value={title} onChange={setTitle} placeholder={cfg.ph} /></Field>
      {type !== 'note' && <Field label="Address"><TextInput icon="map-pin" value="" placeholder="Where is it?" /></Field>}
      {type !== 'note' && <div style={{ marginBottom: 16 }}><MiniMap /></div>}
      <TwoUp>
        <Field label="Date"><TextInput icon="calendar-days" value="24 Apr" mono /></Field>
        <Field label="Time"><TextInput icon="clock" value={type === 'food' ? '20:30' : ''} placeholder="optional" mono /></Field>
      </TwoUp>
      <Field label="Notes"><TextInput value="" placeholder="Anything the group should know…" /></Field>
    </FormShell>
  );
}

// ── Add flow controller — picker → form, returns the new item on save ──────
function AddFlow({ dayLabel, initialType, onClose, onSave }) {
  const [type, setType] = useStateAdd(initialType || null);
  if (!type) return <TypePicker dayLabel={dayLabel} onClose={onClose} onPick={setType} />;
  const common = { dayLabel, onClose, onSave };
  if (type === 'stay') return <StayForm {...common} />;
  if (type === 'ride' || type === 'walk') return <ActivityForm {...common} />;
  if (type === 'flight' || type === 'travel') return <FlightForm {...common} />;
  return <GenericForm type={type === 'place' ? 'poi' : type} {...common} />;
}

Object.assign(window, { ITEM_TYPE, ADD_ORDER, AddFlow, TypePicker, StayForm, ActivityForm, FlightForm, GenericForm,
  Field, FieldLabel, TextInput, TwoUp, Segmented, AttachRow, MiniMap, FormShell });
