// ─────────────────────────────────────────────────────────────────────
// ADD VEHICLE — the redesigned onboarding flow.
//
// Rethought from the ground up: identify the vehicle, give it a face, and
// get into the collection. Only Make · Model · Year and a cover photo are
// required. Nickname is optional; estimated value and status are gone from
// onboarding entirely (they belong to the vehicle record, added later).
//
// Two presentations share the same field components and validation:
//   · GUIDED  — a short 3-step flow (Identify → Cover → Identifier)
//   · SINGLE  — every section on one scroll
// Toggle via the `mode` prop (exposed as a Tweak).
// ─────────────────────────────────────────────────────────────────────

const { useState: useAvF, useRef: useAvFRef, useEffect: useAvFEffect } = React;

// Sample cover photos from the archive — the quick-pick strip so the flow is
// demoable without an upload. A real <input type=file> capture is wired too.
const AV_SAMPLE_PHOTOS = [
  { src: 'images/shelby-cobra-427.jpeg', label: 'Cobra 427' },
  { src: 'images/porsche-911-carrera-rs-2.jpeg', label: 'Carrera RS' },
  { src: 'images/ferrari-275-gtb4.jpeg', label: '275 GTB/4' },
  { src: 'images/mercedes-300sl-gullwing.jpeg', label: '300SL' },
];

const AV_EMPTY = { make: '', makeCode: '', model: '', year: '', nickname: '', photo: '', idType: 'vin', idValue: '' };

// ── Plain labelled field (year, nickname, identifier value) ─────────────
function AvField({ label, optional, value, onChange, placeholder, mono, maxLength, hint }) {
  const active = !!(value && String(value).trim());
  return (
    <div>
      <AvLabel right={optional ? <span style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.12em', textTransform: 'uppercase', color: P.mute }}>Optional</span> : null}>{label}</AvLabel>
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} maxLength={maxLength}
        inputMode={mono ? 'text' : undefined}
        style={{
          width: '100%', height: 46, boxSizing: 'border-box', background: P.ink,
          border: `1px solid ${active ? P.gold : P.slate}`, outline: 'none', color: P.paper,
          fontFamily: mono ? T.mono : T.body, fontSize: 13, padding: '0 14px',
        }} />
      {hint && <div style={{ marginTop: 7, fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.08em', color: P.mute, lineHeight: 1.5 }}>{hint}</div>}
    </div>
  );
}

// ── Guided autocomplete picker (Make, Model) ────────────────────────────
// Search → suggestion rows → pick. Free entry is always allowed via the
// trailing "Use ‘…’" row so coachbuilt one-offs are never blocked.
function GuidedPicker({ label, chosen, chosenSub, chosenThumb, placeholder, results, onPick, onClear, autoFocus }) {
  const [query, setQuery] = useAvF('');
  const ref = useAvFRef(null);
  useAvFEffect(() => { if (autoFocus && ref.current) ref.current.focus(); }, [autoFocus]);

  if (chosen) {
    return (
      <div>
        <AvLabel>{label}</AvLabel>
        <AvChosenRow value={chosen} sub={chosenSub} onChange={() => { onClear(); setQuery(''); }} />
      </div>
    );
  }

  const q = query.trim();
  const rows = q ? results(q) : results('');
  const exact = rows.some(r => r.name.toLowerCase() === q.toLowerCase());

  return (
    <div>
      <AvLabel>{label}</AvLabel>
      <AvSearchField value={query} onChange={setQuery} placeholder={placeholder} inputRef={ref} />
      {(q || rows.length > 0) && (
        <div style={{ marginTop: 8, border: `1px solid ${P.slate}`, maxHeight: 236, overflow: 'auto' }} className="proto-scroll">
          {rows.map((r, i) => (
            <AvRow key={r.name}
              noRadio
              title={r.name}
              sub={r.sub ? <span style={{ display: 'block', fontFamily: T.mono, fontSize: 8, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.mute, marginTop: 3 }}>{r.sub}</span> : null}
              right={<Icon name="add" size={15} color={P.gold} strokeWidth={2} />}
              last={i === rows.length - 1 && exact}
              onClick={() => { onPick(r); setQuery(''); }} />
          ))}
          {q && !exact && (
            <button onClick={() => { onPick({ name: query.trim(), code: query.trim().replace(/[^A-Za-z]/g, '').slice(0, 2).toUpperCase(), free: true }); setQuery(''); }}
              style={{ width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent', border: 'none', borderTop: rows.length ? `1px solid ${P.slate}` : 'none', padding: '12px 13px', display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="add" size={15} color={P.gold} strokeWidth={2} />
              <span style={{ fontFamily: T.body, fontSize: 12.5, color: P.paper }}>Use “<span style={{ fontWeight: 600 }}>{query.trim()}</span>”</span>
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// SECTION 1 — IDENTIFY (Make · Model · Year)
// ═══════════════════════════════════════════════════════════════════════
function IdentifySection({ draft, set, single }) {
  const makeChosen = !!draft.make;
  const modelChosen = !!draft.model;
  return (
    <div style={{ display: 'grid', gap: 18 }}>
      <GuidedPicker
        label="Make"
        placeholder="Search manufacturers"
        chosen={draft.make}
        chosenSub="Manufacturer"
        chosenThumb={<AvMarque code={draft.makeCode} size="sm" />}
        results={(q) => searchMakes(q)}
        onPick={(r) => set({ make: r.name, makeCode: r.code, model: '' })}
        onClear={() => set({ make: '', makeCode: '', model: '' })}
      />

      {makeChosen && (
        <GuidedPicker
          label="Model"
          placeholder={`Search ${draft.make} models`}
          chosen={draft.model}
          chosenSub={draft.make || ''}
          chosenThumb={<AvMarque code={draft.makeCode || '—'} size="sm" />}
          results={(q) => searchModels(draft.make, q).map(m => ({ name: m, code: draft.makeCode }))}
          onPick={(r) => set({ model: r.name })}
          onClear={() => set({ model: '' })}
          autoFocus={makeChosen && !single}
        />
      )}

      {modelChosen && (
        <AvField label="Year" value={draft.year} onChange={(v) => set({ year: v.replace(/[^0-9]/g, '').slice(0, 4) })} placeholder="Enter year" mono maxLength={4} />
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// SECTION 2 — COVER PHOTO (required) + optional nickname
// ═══════════════════════════════════════════════════════════════════════
function CoverSection({ draft, set }) {
  const fileRef = useAvFRef(null);
  const camRef = useAvFRef(null);
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => set({ photo: reader.result });
    reader.readAsDataURL(f);
  };
  // Reuses the Upload Expense "Capture the source" selector — Camera + Photos
  // (no PDF; a cover photo is always an image). Camera opens the device
  // capture; Photos opens the library picker.
  const methods = [
    { id: 'camera', icon: 'camera', label: 'Camera', open: () => camRef.current && camRef.current.click() },
    { id: 'photos', icon: 'gallery', label: 'Photos', open: () => fileRef.current && fileRef.current.click() },
  ];
  return (
    <div style={{ display: 'grid', gap: 18 }}>
      <div>
        <input ref={fileRef} type="file" accept="image/*" onChange={onFile} style={{ display: 'none' }} />
        <input ref={camRef} type="file" accept="image/*" capture="environment" onChange={onFile} style={{ display: 'none' }} />

        {/* Preview — only shown once a photo has been added */}
        {draft.photo && (
          <button onClick={() => fileRef.current && fileRef.current.click()} style={{
            width: '100%', padding: 0, border: `1px solid ${P.slate}`, background: 'transparent', cursor: 'pointer', display: 'block', position: 'relative', marginBottom: 8,
          }}>
            <PhotoSlot dirId="concours" height={214} tone="dark" cover src={draft.photo} />
            <span style={{ position: 'absolute', bottom: 10, right: 10, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 11px', background: 'rgba(10,10,11,0.7)', border: `1px solid ${P.gold}`, backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)', fontFamily: T.mono, fontSize: 8.5, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: P.gold }}>
              <Icon name="camera" size={12} color={P.gold} strokeWidth={1.8} /> Change
            </span>
          </button>
        )}

        {/* Capture methods — same segmented pattern as Upload Expense */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {methods.map(m => (
            <button key={m.id} onClick={m.open} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
              padding: '16px 8px', cursor: 'pointer', background: 'transparent',
              border: `1px solid ${P.gold}`, transition: 'border-color .15s, background .15s',
            }}>
              <Icon name={m.icon} size={22} color={P.gold} strokeWidth={1.5} />
              <span style={{ fontFamily: T.mono, fontSize: 9, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: P.paper }}>{m.label}</span>
            </button>
          ))}
        </div>
      </div>

      <AvField label="Nickname" optional value={draft.nickname} onChange={(v) => set({ nickname: v })} placeholder="Enter nickname" maxLength={40} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// SECTION 3 — VEHICLE IDENTIFIER (neutral term here; typed everywhere else)
// ═══════════════════════════════════════════════════════════════════════
function IdentifierSection({ draft, set }) {
  const type = AV_IDENTIFIER_BY_ID[draft.idType];
  const preview = type && type.holder && draft.idValue.trim() ? maskIdentifier(draft.idValue) : null;
  return (
    <div style={{ display: 'grid', gap: 18 }}>
      <div>
        <div style={{ border: `1px solid ${P.slate}` }}>
          {AV_IDENTIFIER_TYPES.map((t, i) => (
            <AvRow key={t.id}
              selected={draft.idType === t.id}
              onClick={() => set({ idType: t.id, idValue: t.holder ? draft.idValue : '' })}
              last={i === AV_IDENTIFIER_TYPES.length - 1}
              title={t.label}
              thumb={null}
              sub={<span style={{ display: 'block', fontFamily: T.body, fontSize: 11, color: P.mute, marginTop: 3, lineHeight: 1.4, whiteSpace: 'normal' }}>{t.full}</span>}
            />
          ))}
        </div>
      </div>

      {type && type.holder && (
        <div>
          <AvField label={`${type.label} Value`} value={draft.idValue} onChange={(v) => set({ idValue: v })} placeholder={`Enter ${type.label}`} mono />
          {preview && (
            <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: P.graphite, borderLeft: `2px solid ${P.gold}` }}>
              <span style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.16em', textTransform: 'uppercase', color: P.mute }}>Will display as</span>
              <span style={{ fontFamily: T.mono, fontSize: 12, letterSpacing: '0.06em', color: P.paper }}>{type.display} {preview}</span>
            </div>
          )}
        </div>
      )}

      {type && !type.holder && (
        <div style={{ padding: '12px 14px', background: P.graphite, borderLeft: `2px solid ${P.slate}`, fontFamily: T.body, fontSize: 11.5, color: P.bone, lineHeight: 1.5 }}>
          No identifier is required to create the vehicle. Add a VIN, chassis, engine or body number anytime from its record.
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  AV_EMPTY, AV_SAMPLE_PHOTOS,
  AvField, GuidedPicker, IdentifySection, CoverSection, IdentifierSection,
});
