// Main app — garage ↔ vehicle router.
// Home is the collection dashboard; tapping a vehicle opens its detail
// screen set (which differs for active vs sold vehicles).

const { useState: useStateA, useRef: useRefA, useEffect: useEffectA } = React;

// Screen registry — resolves a section id to a component for a vehicle.
function screenComponent(sectionId, vehicle) {
  const sold = vehicle.status === 'Sold';
  switch (sectionId) {
    case 'overview':   return sold ? ScreenSoldOverview : ScreenOverview;
    case 'gallery':    return ScreenGallery;
    case 'timeline':   return ScreenTimeline;
    case 'provenance': return ScreenProvenance;
    case 'value':      return ScreenValue;
    case 'sale':       return ScreenSale;
    case 'service':    return ScreenService;
    case 'documents':  return ScreenVault;
    default:           return ScreenOverview;
  }
}

function VehicleDetail({ vehicle, onBack, onEdit, onDelete }) {
  const sections = sectionsFor(vehicle);
  // Deep link to a photo lands on the gallery section.
  const [section, setSection] = useStateA(() => (window.__vrPendingPhoto ? 'gallery' : sections[0].id));
  const scrollRef = useRefA(null);

  useEffectA(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [section]);

  const Active = screenComponent(section, vehicle);
  const idx = sections.findIndex(s => s.id === section) + 1;

  return (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', background: P.ink }}>
      <ProtoHeader vehicle={vehicle} onBack={onBack} onEdit={onEdit} onDelete={onDelete} />
      <ProtoSectionTabs active={section} onChange={setSection} sections={sections} />
      <div ref={scrollRef} className="proto-scroll" style={{
        flex: 1, overflow: 'auto', background: P.ink,
      }} data-screen-label={`${idx}-${section}`}>
        <Active key={vehicle.id + ':' + section} vehicle={vehicle} />
      </div>
    </div>
  );
}

// Centered confirm modal for destructive removal.
function ConfirmRemove({ vehicle, onCancel, onConfirm }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 90,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}>
      <div onClick={onCancel} style={{
        position: 'absolute', inset: 0, background: 'rgba(10,10,11,0.82)',
        backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
      }} />
      <div style={{
        position: 'relative', width: '100%', background: P.graphite,
        border: `1px solid ${P.signal}`, padding: 22,
      }}>
        <Eyebrow color={P.signal}>REMOVE FROM COLLECTION</Eyebrow>
        <div style={{
          fontFamily: T.display, fontSize: 22, fontWeight: 700,
          color: P.paper, marginTop: 8, letterSpacing: '-0.015em', lineHeight: 1.05,
        }}>{vehicle.year} {vehicle.make} {vehicle.model}</div>
        <div style={{
          fontFamily: T.body, fontSize: 12, color: P.bone, marginTop: 10, lineHeight: 1.5,
        }}>
          This removes "{vehicle.nickname}" and its entire record from your collection.
          This can't be undone in the prototype.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 8, marginTop: 20 }}>
          <button onClick={onCancel} style={{
            height: 46, background: 'transparent', border: `1px solid ${P.slate}`,
            color: P.paper, fontFamily: T.mono, fontSize: 10, fontWeight: 600,
            letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer',
          }}>KEEP</button>
          <button onClick={onConfirm} style={{
            height: 46, background: P.signal, border: `1px solid ${P.signal}`,
            color: P.paper, fontFamily: T.mono, fontSize: 10, fontWeight: 700,
            letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer',
          }}>REMOVE</button>
        </div>
      </div>
    </div>
  );
}

function ProtoApp() {
  // Session collection — starts with Old Yeller (active) + Ferrari (sold).
  const [vehicles, setVehicles] = useStateA([VEHICLE, VEHICLE_FERRARI, VEHICLE_MERCEDES]);
  // Cold-load deep link: #p=<vehicleId>~<photoId> opens that vehicle's gallery.
  const [openId, setOpenId] = useStateA(() => {
    const m = /[#&]p=([^&]+)/.exec(window.location.hash || '');
    if (m) {
      const [vid, pid] = decodeURIComponent(m[1]).split('~');
      window.__vrPendingPhoto = pid;
      return vid;
    }
    return null;
  });   // null = garage
  const [editing, setEditing] = useStateA(null);  // vehicle being edited
  const [removing, setRemoving] = useStateA(null); // vehicle pending removal

  const openVehicle = (id) => setOpenId(id);
  const back = () => setOpenId(null);

  const addVehicle = (veh) => setVehicles(prev => [...prev, veh]);
  const updateVehicle = (veh) => setVehicles(prev => prev.map(v => {
    if (v.id !== veh.id) return v;
    // Preserve rich nested value data (appraisals, investments) when the
    // edit sheet only supplies a new current estimate.
    const merged = { ...v, ...veh };
    if (v.value && veh.value) merged.value = { ...v.value, ...veh.value };
    return merged;
  }));
  const deleteVehicle = (veh) => {
    setVehicles(prev => prev.filter(v => v.id !== veh.id));
    if (openId === veh.id) setOpenId(null);
  };

  const active = openId ? vehicles.find(v => v.id === openId) : null;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      minHeight: '100vh', width: '100%', background: '#0a0a0b',
    }}>
      <IOSDevice dark width={402} height={874}>
        <div id="proto-stage" style={{ height: '100%', display: 'flex', flexDirection: 'column', background: P.ink, position: 'relative' }}>
          {/* iOS status bar spacer */}
          <div style={{ height: 54, flex: '0 0 auto' }} />

          {active ? (
            <VehicleDetail
              vehicle={active}
              onBack={back}
              onEdit={(v) => setEditing(v)}
              onDelete={(v) => setRemoving(v)}
            />
          ) : (
            <Garage
              vehicles={vehicles}
              onOpen={openVehicle}
              onAdd={addVehicle}
            />
          )}

          {/* Home indicator spacer */}
          <div style={{ height: 28, flex: '0 0 auto', background: P.ink }} />

          {/* Edit sheet (detail) */}
          {editing && (
            <VehicleSheet
              existing={editing}
              onClose={() => setEditing(null)}
              onSave={(veh) => updateVehicle(veh)}
            />
          )}

          {/* Remove confirm (detail) */}
          {removing && (
            <ConfirmRemove
              vehicle={removing}
              onCancel={() => setRemoving(null)}
              onConfirm={() => { deleteVehicle(removing); setRemoving(null); }}
            />
          )}
        </div>
      </IOSDevice>
    </div>
  );
}

const protoRoot = ReactDOM.createRoot(document.getElementById('root'));
protoRoot.render(<ProtoApp />);
