// GARAGE — the collection dashboard / landing page.
// Lists every vehicle, supports search · filter · sort · add · edit · delete,
// and routes into each vehicle's detail screens.

const { useState: useG } = React;

// Partial VIN — mask all but the last four, consistently.
function partialVin(vin) {
  if (!vin) return '—';
  if (vin.length <= 4) return vin.toUpperCase();
  return '•••• ' + vin.slice(-4).toUpperCase();
}

// ─────────────────────────────────────────────────────────────────────
// VEHICLE CARD
// ─────────────────────────────────────────────────────────────────────

function VehicleCard({ v, onOpen }) {
  // Financial panel is ALWAYS present so every card keeps one structure:
  //   sold price → SOLD FOR · price · est value → EST. VALUE · price
  //   neither    → EST. VALUE · "Awaiting Valuation" (muted, informative)
  const soldPrice = v.sale && v.sale.price != null ? v.sale.price : null;
  const estValue = v.value && v.value.current != null ? v.value.current : null;
  const isSold = v.status === 'Sold' || soldPrice != null;
  const finLabel = isSold ? 'SOLD FOR' : 'EST. VALUE';
  const finAmount = isSold ? soldPrice : estValue;
  // Primary identifier shown with its ACTUAL type — "Chassis ••••8475".
  const idLabel = identifierLabel(v);

  return (
    <div onClick={() => onOpen(v.id)} style={{
      background: P.graphite,
      border: `1px solid ${P.graphite}`,
      marginBottom: 12,
      cursor: 'pointer',
    }}>
      {/* Hero */}
      <div style={{ position: 'relative' }}>
        <PhotoSlot dirId="concours" height={184} tone="dark" cover
          src={v.hero || undefined}
          label={v.hero ? '' : `${v.year} ${v.make.toUpperCase()} ${v.model.toUpperCase()}`}
          sub={v.hero ? '' : 'NO IMAGE'} />
        {/* Gradient for legibility */}
        <div style={{
          position: 'absolute', inset: 0,
          background: isSold
            ? 'linear-gradient(to bottom, rgba(10,10,11,0.35) 0%, rgba(10,10,11,0.15) 40%, rgba(10,10,11,0.85) 100%)'
            : 'linear-gradient(to bottom, rgba(10,10,11,0) 35%, rgba(10,10,11,0.85) 100%)',
        }} />
        {/* Status chip — only when a status is recorded */}
        {v.status && (
          <div style={{ position: 'absolute', top: 12, left: 12 }}>
            <VehicleStatusChip status={v.status} />
          </div>
        )}
      </div>

      {/* Body */}
      <div style={{ padding: '14px 16px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'stretch', gap: 12 }}>
          <div style={{ minWidth: 0 }}>
            <Eyebrow color={P.gold}>{v.year} · {v.make.toUpperCase()}</Eyebrow>
            <div style={{
              fontFamily: T.display, fontSize: 22, fontWeight: 700,
              color: P.paper, letterSpacing: '-0.01em', lineHeight: 1, marginTop: 5,
            }}>{v.model.toUpperCase()}</div>
            {v.nickname
              ? <div style={{
                  fontFamily: T.body, fontSize: 12, color: P.mute, marginTop: 5,
                }}>"{v.nickname}"</div>
              : null}
          </div>
          {/* Value — bordered frame, always shown for a consistent layout */}
          <div style={{
            textAlign: 'center', flexShrink: 0,
            display: 'flex', flexDirection: 'column', justifyContent: 'center',
            border: 'none', background: '#15140F', padding: '8px 12px 12px',
          }}>
            <div style={{
              fontFamily: T.mono, fontSize: 8, letterSpacing: '0.18em',
              textTransform: 'uppercase', color: P.mute,
            }}>{finLabel}</div>
            {finAmount != null
              ? <div style={{
                  fontFamily: T.display, fontSize: 22, fontWeight: 700,
                  color: P.paper, letterSpacing: '-0.02em', lineHeight: 1, marginTop: 4,
                }}>{fmtMoney(finAmount, { compact: true })}</div>
              : <div style={{
                  fontFamily: T.body, fontSize: 12, fontWeight: 400,
                  color: P.mute, lineHeight: 1.2, marginTop: 6, whiteSpace: 'nowrap',
                }}>Awaiting Valuation</div>}
          </div>
        </div>

        <div style={{
          marginTop: 12, paddingTop: 10, borderTop: `1px solid ${P.slate}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            fontFamily: T.mono, fontSize: 9, color: idLabel ? P.mute : P.slate,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{idLabel ? `${idLabel.display} ${idLabel.masked}` : 'No Identifier Yet'}</div>
          <div style={{
            fontFamily: T.mono, fontSize: 9, color: P.mute,
            letterSpacing: '0.12em', textTransform: 'uppercase', flexShrink: 0,
          }}>UPD {v.lastUpdated}</div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// ADD / EDIT SHEET
// ─────────────────────────────────────────────────────────────────────

function VehicleSheet({ existing, onClose, onSave, fromNav = false, initialStatus }) {
  const [year, setYear] = useG(existing ? String(existing.year) : '');
  const [make, setMake] = useG(existing ? existing.make : '');
  const [model, setModel] = useG(existing ? existing.model : '');
  const [nickname, setNick] = useG(existing ? existing.nickname : '');
  const [vin, setVin] = useG(existing ? existing.vin : '');
  const [value, setValue] = useG(existing ? String((existing.value && existing.value.current) || '') : '');
  const [status, setStatus] = useG(existing ? existing.status : (initialStatus || 'Active'));
  const [closing, setClosing] = useG(false);

  // Slide back down (collection) or fade out (nav) before unmounting.
  const requestClose = () => {
    if (closing) return;
    setClosing(true);
    setTimeout(() => { onClose && onClose(); }, fromNav ? 400 : 550);
  };

  const Field = ({ label, value, onChange, placeholder, mono }) => (
    <div style={{ minWidth: 0 }}>
      <div style={{
        fontFamily: T.mono, fontSize: 9, letterSpacing: '0.2em',
        textTransform: 'uppercase', color: P.mute, marginBottom: 6,
      }}>{label}</div>
      <div style={{
        height: 42, border: `1px solid ${P.slate}`, background: P.ink,
        display: 'flex', alignItems: 'center', padding: '0 12px', minWidth: 0,
      }}>
        <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
          style={{
            flex: 1, minWidth: 0, width: '100%',
            background: 'transparent', border: 'none', outline: 'none',
            color: P.paper, fontFamily: mono ? T.mono : T.body, fontSize: 13,
          }} />
      </div>
    </div>
  );

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 80,
      background: P.graphite, color: P.paper,
      display: 'flex', flexDirection: 'column',
      animation: closing
        ? (fromNav ? 'addFadeOut .4s ease forwards' : 'addPageDown .55s cubic-bezier(.16,.84,.3,1) forwards')
        : (fromNav ? 'none' : 'addPageUp .55s cubic-bezier(.16,.84,.3,1) forwards'),
    }}>
      {/* status-bar spacer to match the app shell */}
      <div style={{ height: 54, flex: '0 0 auto', background: P.graphite }} />
      <div className="proto-scroll" style={{
        flex: 1, overflow: 'auto', padding: '8px 22px 18px',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div>
            <Eyebrow color={P.gold}>{existing ? 'EDIT VEHICLE' : 'NEW VEHICLE'}</Eyebrow>
            <div style={{
              fontFamily: T.display, fontSize: 24, fontWeight: 700,
              color: P.paper, marginTop: 6, letterSpacing: '-0.015em',
            }}>{existing ? 'UPDATE DETAILS' : 'ADD TO COLLECTION'}</div>
          </div>
        </div>

        <div style={{ display: 'grid', gap: 14, marginBottom: 18 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr', gap: 14 }}>
            <Field label="Year" value={year} onChange={setYear} placeholder="1967" mono />
            <Field label="Make" value={make} onChange={setMake} placeholder="Ferrari" />
          </div>
          <Field label="Model" value={model} onChange={setModel} placeholder="275 GTB/4" />
          <Field label="Nickname" value={nickname} onChange={setNick} placeholder="The Maranello Four-Cam" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div style={{ minWidth: 0 }}>
              <Field label="VIN" value={vin} onChange={setVin} placeholder="09437" mono />
              <div style={{
                marginTop: 6, fontFamily: T.mono, fontSize: 9, color: P.mute,
                letterSpacing: '0.14em', textTransform: 'uppercase',
              }}>ON CARDS · {partialVin(vin)}</div>
            </div>
            <Field label="Est. value (USD)" value={value} onChange={setValue} placeholder="1250000" mono />
          </div>
          {/* Status */}
          <div>
            <div style={{
              fontFamily: T.mono, fontSize: 9, letterSpacing: '0.2em',
              textTransform: 'uppercase', color: P.mute, marginBottom: 6,
            }}>Status</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {['Active', 'In Restoration', 'In Storage', 'Evaluating', 'For Sale', 'Sold', 'Archived'].map(st => {
                const on = status === st;
                return (
                  <button key={st} onClick={() => setStatus(st)} style={{
                    padding: '8px 12px',
                    background: on ? P.paper : 'transparent',
                    color: on ? P.ink : P.paper,
                    border: `1px solid ${on ? P.paper : P.slate}`,
                    fontFamily: T.mono, fontSize: 9, fontWeight: 600,
                    letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer',
                  }}>{st}</button>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* sticky action footer — matches the action sheets */}
      <div style={{
        flex: '0 0 auto', background: P.graphite, borderTop: `1px solid ${P.slate}`,
        padding: '14px 22px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
      }}>
        <button onClick={requestClose} style={{
          height: 48, background: 'transparent', border: `1px solid ${P.slate}`,
          color: P.paper, fontFamily: T.mono, fontSize: 10, fontWeight: 600,
          letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer',
        }}>CANCEL</button>
        <button
          onClick={() => {
            // NOTE: new-vehicle creation is intentionally disabled until the full
            // flow is built. Editing an existing vehicle still saves.
            if (existing) {
              onSave({
                id: existing.id,
                year: parseInt(year) || '—', make, model, nickname, vin,
                status,
                value: { current: parseInt(value) || 0 },
                lastUpdated: 'Just now',
                hero: existing.hero,
                _draft: existing._draft,
              });
            }
            requestClose();
          }}
          style={{
            height: 48, background: P.gold, color: P.ink, border: `1px solid ${P.gold}`,
            fontFamily: T.mono, fontSize: 10, fontWeight: 700,
            letterSpacing: '0.22em', textTransform: 'uppercase', cursor: 'pointer',
          }}>{existing ? 'SAVE CHANGES' : 'ADD VEHICLE'}</button>
      </div>
      {/* home-indicator spacer */}
      <div style={{ height: 28, flex: '0 0 auto', background: P.graphite }} />
      <style>{`@keyframes addPageUp { from { transform: translateY(100%) } to { transform: none } } @keyframes addPageDown { from { transform: none } to { transform: translateY(100%) } } @keyframes addFadeOut { from { opacity: 1 } to { opacity: 0 } }`}</style>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// GARAGE SCREEN
// ─────────────────────────────────────────────────────────────────────

// Recursively flatten every string/number in a vehicle record into one
// lowercase haystack. Cached per-record so typing stays snappy.
const _searchCache = new WeakMap();
function deepSearchText(v) {
  if (v && typeof v === 'object' && _searchCache.has(v)) return _searchCache.get(v);
  const out = [];
  const walk = (node) => {
    if (node == null) return;
    if (typeof node === 'string' || typeof node === 'number') { out.push(String(node)); return; }
    if (Array.isArray(node)) { node.forEach(walk); return; }
    if (typeof node === 'object') { for (const k in node) walk(node[k]); }
  };
  walk(v);
  const hay = out.join(' ').toLowerCase();
  if (v && typeof v === 'object') _searchCache.set(v, hay);
  return hay;
}

function Garage({ vehicles, onOpen, onAdd }) {
  const [query, setQuery] = useG('');
  const [filter, setFilter] = useG('All');     // All | Active | Sold
  const [sheet, setSheet] = useG(null);          // null | {} (new)
  const [showOps, setShowOps] = useG(false);     // Collection Operations hub
  const [opsView, setOpsView] = useG('menu');    // which view ops opens to

  // Filter
  let list = vehicles.filter(v => {
    if (filter === 'Active') return v.status !== 'Sold' && v.status !== 'Archived';
    if (filter === 'Sold') return v.status === 'Sold' || v.status === 'Archived';
    return true;
  });
  // Search — match against EVERYTHING known about the car (specs, parts,
  // documents, service records, provenance, health notes, etc.) so a query
  // like "Recaro" surfaces any car whose seats/parts/docs mention it.
  const q = query.trim().toLowerCase();
  if (q) {
    const terms = q.split(/\s+/);
    list = list.filter(v => {
      const hay = deepSearchText(v);
      return terms.every(t => hay.includes(t));
    });
  }
  // Sort: newest-added first (so a just-added vehicle lands at the top),
  // then Make → Model → Year.
  list = [...list].sort((a, b) =>
    ((b.isNew ? 1 : 0) - (a.isNew ? 1 : 0)) ||
    (a.make || '').localeCompare(b.make || '') ||
    (a.model || '').localeCompare(b.model || '') ||
    (a.year || 0) - (b.year || 0)
  );

  // Collection stats
  const activeVehicles = vehicles.filter(v => v.status !== 'Sold' && v.status !== 'Archived');
  const soldVehicles = vehicles.filter(v => v.status === 'Sold' || v.status === 'Archived');
  const collectionValue = activeVehicles.reduce((s, v) => s + ((v.value && v.value.current) || 0), 0);

  const counts = { All: vehicles.length, Active: activeVehicles.length, Sold: soldVehicles.length };

  return (
    <div style={{
      flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column',
      background: P.ink, color: P.paper, position: 'relative',
    }}>
      {/* App header */}
      <div style={{
        padding: '14px 22px 8px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        flex: '0 0 auto',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <CAMonogram size={20} color={P.paper} stroke={1.6} />
          <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 700, letterSpacing: '0.06em' }}>
            COLLECTOR / ARCHIVES
          </div>
        </div>
        {/* Operations menu */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {/* Operations menu — opens the platform navigation */}
          <button onClick={() => { setOpsView('menu'); setShowOps(true); }} aria-label="Open operations menu" style={{
            width: 38, height: 38, flexShrink: 0, borderRadius: 999, cursor: 'pointer',
            background: 'transparent', border: `1px solid ${P.gold}`, color: P.paper,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
          }}>
            <span style={{ width: 16, height: 1.6, background: P.gold, display: 'block' }} />
            <span style={{ width: 16, height: 1.6, background: P.gold, display: 'block' }} />
            <span style={{ width: 16, height: 1.6, background: P.gold, display: 'block' }} />
          </button>
        </div>
      </div>

      {/* Scroll body */}
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto' }}>
        {/* Editorial title + stats */}
        <div style={{ padding: '14px 22px 18px' }}>
          <div style={{
            fontFamily: T.display, fontWeight: 700, fontSize: 46,
            lineHeight: 0.88, letterSpacing: '-0.02em',
          }}>THE<br/>COLLECTION</div>
          <Eyebrow color={P.gold} style={{ display: 'block', marginTop: 12 }}>Managed by {(typeof COLLECTION_MANAGER !== 'undefined' ? COLLECTION_MANAGER.name : 'Jeff Smith')}</Eyebrow>
        </div>

        {/* Search */}
        <div style={{ padding: '0 22px 12px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 14px', border: `1px solid ${P.slate}`, background: P.graphite,
          }}>
            <Icon name="search" size={14} color={P.mute} />
            <input value={query} onChange={(e) => setQuery(e.target.value)}
              placeholder="Search"
              style={{
                flex: 1, background: 'transparent', border: 'none', outline: 'none',
                color: P.paper, fontFamily: T.body, fontSize: 13,
              }} />
            {query && (
              <button onClick={() => setQuery('')} style={{
                background: 'transparent', border: 'none', color: P.gold, cursor: 'pointer',
                fontFamily: T.mono, fontSize: 14,
              }}>×</button>
            )}
          </div>
        </div>

        {/* Filter + sort row */}
        <div style={{
          padding: '0 22px 14px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        }}>
          <div style={{ display: 'inline-flex', border: `1px solid ${P.slate}` }}>
            {['All', 'Active', 'Sold'].map((f, i) => {
              const on = filter === f;
              return (
                <button key={f} onClick={() => setFilter(f)} style={{
                  padding: '9px 14px',
                  background: on ? P.paper : 'transparent',
                  color: on ? P.ink : P.paper,
                  border: 'none', borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none',
                  fontFamily: T.mono, fontSize: 9, fontWeight: 600,
                  letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer',
                  display: 'inline-flex', gap: 6, alignItems: 'center',
                }}>
                  {f}<span style={{ color: on ? P.gold : P.mute }}>{counts[f]}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Cards */}
        <div style={{ padding: '0 22px 8px' }}>
          {list.length === 0 ? (
            <div style={{
              padding: '48px 16px', textAlign: 'center',
              fontFamily: T.mono, fontSize: 10, color: P.mute,
              letterSpacing: '0.16em', textTransform: 'uppercase',
            }}>No vehicles match.</div>
          ) : list.map(v => (
            <VehicleCard key={v.id} v={v} onOpen={onOpen} />
          ))}
        </div>

        <div style={{ height: 12 }} />
      </div>

      {/* Add Vehicle — the redesigned guided flow (launched from the
          Operations Hub). Editing an existing vehicle still uses VehicleSheet. */}
      {sheet && (
        <AddVehicleFlow
          onClose={() => setSheet(null)}
          onCreate={(veh) => { onAdd(veh); setSheet(null); }}
        />
      )}

      {/* Collection Operations — full-screen command center */}
      {showOps && (
        <OperationsFlow
          vehicles={vehicles}
          initialView={opsView}
          onClose={() => setShowOps(false)}
          onAddVehicle={() => { setSheet({ fromNav: true }); }}
        />
      )}
    </div>
  );
}

Object.assign(window, { Garage, VehicleCard, VehicleSheet, partialVin });
