// ─────────────────────────────────────────────────────────────────────
// ADD VEHICLE — flow controller (shell, progress, validation, success).
// Routes the three sections as a guided 3-step flow or a single scroll,
// enforces the minimum required fields, and writes the record.
// ─────────────────────────────────────────────────────────────────────

const { useState: useAvC } = React;

const AV_STEPS = [
  { id: 'identify',   label: 'Identify',   eyebrow: 'STEP 1 / 3', title: 'IDENTIFY THE\nVEHICLE', lead: 'Start with what it is. Suggestions keep the archive consistent.' },
  { id: 'cover',      label: 'Cover',      eyebrow: 'STEP 2 / 3', title: 'ADD A COVER\nPHOTO', lead: 'This becomes the hero image across your collection.' },
  { id: 'identifier', label: 'Identifier', eyebrow: 'STEP 3 / 3', title: 'VEHICLE\nIDENTIFIER', lead: 'Choose how this vehicle is identified. Both the type and value are stored.' },
];

// Field requirements per section.
function identifyValid(d) { return !!(d.make && d.model && d.year && d.year.length === 4); }
function coverValid(d) { return !!d.photo; }
function identifierValid(d) {
  const t = AV_IDENTIFIER_BY_ID[d.idType];
  if (!t) return false;
  return t.holder ? !!d.idValue.trim() : true;
}
function allValid(d) { return identifyValid(d) && coverValid(d) && identifierValid(d); }

// Assemble the record. No status, no estimated value — those belong to the
// vehicle record and are added later, never at onboarding. Sparse sections
// are scaffolded with safe empties so the vehicle's detail view renders
// (as an empty record ready to grow) rather than crashing.
function buildVehicle(d) {
  const idValue = d.idValue.trim();
  return {
    id: 'new-' + Date.now(),
    hero: d.photo,
    year: parseInt(d.year, 10),
    make: d.make,
    model: d.model,
    nickname: (d.nickname || '').trim(),
    // Stored identifier: both type and value. `vin` mirrors the value for
    // back-compat with anything still reading a bare vin string.
    identifier: d.idType === 'later' ? null : { type: d.idType, value: idValue },
    vin: d.idType !== 'later' ? idValue : '',
    status: null,
    // Financial: unknown at creation → card shows "Awaiting Valuation".
    value: { current: null, purchased: null, purchasedAt: '—', purchasedDate: '—', deltaTotal: 0, deltaPct: 0, appraisals: [], investments: [] },
    sale: null,
    lastUpdated: 'Just now',
    isNew: true,
    // Safe scaffolding for the detail screens.
    trim: '—', plate: '—', color: '—', mileage: 0,
    ownership: { since: '—', years: 0, months: 0 },
    location: { name: '—', city: '—', movedDate: '—', climate: '—', other: [] },
    attention: [], health: [], timeline: [], ownership_chain: [],
    provenance: { matchingVin: false, originalEngine: false, originalTrans: false, awards: [], significance: [], docs: [] },
    statusOptions: ['Active', 'In Restoration', 'In Storage', 'Evaluating', 'For Sale', 'Sold', 'Archived'],
  };
}

// Thin 3-segment progress rail.
function AvProgress_UNUSED() { return null; }

function AvHeader({ onClose }) {
  return (
    <div style={{
      padding: '10px 18px 12px', background: P.ink,
      display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: `1px solid ${P.graphite}`, flex: '0 0 auto',
    }}>
      <button onClick={onClose} aria-label="Back" style={{
        background: P.gold, border: 'none', borderRadius: 999,
        width: 34, height: 34, flexShrink: 0, color: P.ink, cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
          <path d="M19 12H5M5 12l6-6M5 12l6 6" />
        </svg>
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: T.display, fontWeight: 600, fontSize: 15, letterSpacing: '0.02em', color: P.paper, lineHeight: 1.1 }}>Add Vehicle</div>
        <div style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.16em', color: P.gold, marginTop: 3 }}>VEHICLES</div>
      </div>
      <CAMonogram size={20} color={P.paper} stroke={1.6} />
    </div>
  );
}

function AvFooter({ backLabel, onBack, primaryLabel, onPrimary, enabled, note }) {
  return (
    <div style={{ flex: '0 0 auto', background: P.graphite, borderTop: `1px solid ${P.slate}`, padding: '14px 22px' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 8 }}>
        <button onClick={onBack} style={{ height: 50, background: 'transparent', border: `1px solid ${P.slate}`, color: P.paper, fontFamily: T.mono, fontSize: 10, fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer' }}>{backLabel}</button>
        <button onClick={enabled ? onPrimary : undefined} disabled={!enabled} style={{
          height: 50, background: enabled ? P.gold : 'transparent', border: `1px solid ${enabled ? P.gold : P.slate}`, color: enabled ? P.ink : P.mute,
          fontFamily: T.mono, fontSize: 10, fontWeight: 700, letterSpacing: '0.2em', textTransform: 'uppercase', cursor: enabled ? 'pointer' : 'not-allowed',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
        }}>
          {primaryLabel}
          {enabled && <Icon name="arrow" size={15} color={P.ink} strokeWidth={2} />}
        </button>
      </div>
      {note && <div style={{ textAlign: 'center', marginTop: 10, fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.mute }}>{note}</div>}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// FLOW CONTROLLER
// ═══════════════════════════════════════════════════════════════════════
function AddVehicleFlow({ initialIdType = 'vin', onClose, onCreate }) {
  const [draft, setDraft] = useAvC({ ...AV_EMPTY, idType: initialIdType });
  const set = (patch) => setDraft(d => ({ ...d, ...patch }));

  // Adding from the Operations Hub returns straight to the collection with
  // the new vehicle in place — no first-run welcome screen.
  const submit = () => { onCreate(buildVehicle(draft)); };

  // ── SINGLE-SCREEN — every section on one scroll ────────────────────
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 80, background: P.ink, display: 'flex', flexDirection: 'column' }}>
      <div style={{ height: 54, flex: '0 0 auto' }} />
      <AvHeader onClose={onClose} />
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto' }}>
        <div style={{ padding: '10px 22px 4px' }}>
          <Eyebrow color={P.gold}>New Vehicle</Eyebrow>
          <div style={{ fontFamily: T.display, fontSize: 40, fontWeight: 700, lineHeight: 0.9, letterSpacing: '-0.02em', color: P.paper, marginTop: 10 }}>ADD TO<br />COLLECTION</div>
        </div>
        <div style={{ padding: '18px 22px 0' }}><RowRuleInline>Add Cover Photo</RowRuleInline></div>
        <div style={{ padding: '14px 22px 6px' }}><CoverSection draft={draft} set={set} /></div>
        <div style={{ padding: '36px 22px 0' }}><RowRuleInline>Identity</RowRuleInline></div>
        <div style={{ padding: '14px 22px 6px' }}><IdentifySection draft={draft} set={set} /></div>
        <div style={{ padding: '36px 22px 0' }}><RowRuleInline>Vehicle Identifier</RowRuleInline></div>
        <div style={{ padding: '14px 22px 20px' }}><IdentifierSection draft={draft} set={set} /></div>
      </div>
      <AvFooter backLabel="Cancel" onBack={onClose} primaryLabel="Add to Collection" onPrimary={submit} enabled={allValid(draft)}
        note={allValid(draft) ? null : 'Make · model · year · cover photo required'} />
      <div style={{ height: 28, flex: '0 0 auto', background: P.graphite }} />
    </div>
  );
}

// Inline editorial rule (label + hairline) for the single-screen sections.
function RowRuleInline({ children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase', color: P.mute, whiteSpace: 'nowrap' }}>{children}</div>
      <div style={{ flex: 1, height: 1, background: P.graphite }} />
    </div>
  );
}

Object.assign(window, { AddVehicleFlow, AV_STEPS, buildVehicle, allValid });
