// ─────────────────────────────────────────────────────────────────────
// SHARED VEHICLE ASSIGNMENT — the one pattern for every non-financial
// record (photos · videos · documents) that needs to point at a vehicle.
//
// This is a SIMPLIFIED sibling of the Upload Expense AllocatorSheet: same
// search field, same SelectRow / VehSub / MarqueThumb primitives, same
// "current assignment + match reasoning" layout — but with everything
// specific to money and multi-vehicle splitting removed. Photos, videos,
// and documents are never split, never "Collection Overhead", and are
// never left with "No Assignment" — they belong to exactly one vehicle.
//
// Used identically by the Collection Manager (to correct a contributor's
// assignment before filing) and the Contributor (to assign their own
// submission at upload time). One component, one interaction, everywhere.
// ─────────────────────────────────────────────────────────────────────

const { useState: useAvA } = React;

// ── the current-assignment row shown inline on a review/upload screen ──
// Tap "Change" (or the row itself) to open the sheet.
function VehicleAssignRow({ vehicle, label = 'ASSIGNED TO', onChange }) {
  return (
    <div>
      <AllocSectionLabel>{label}</AllocSectionLabel>
      <button onClick={onChange} style={{
        width: '100%', textAlign: 'left', cursor: 'pointer', background: 'transparent',
        border: `1px solid ${P.slate}`, padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        {vehicle
          ? <MarqueThumb v={vehicle} />
          : <span style={{ width: 38, height: 48, flexShrink: 0, border: `1px solid ${P.slate}`, background: P.ink, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="car" size={16} color={P.mute} strokeWidth={1.6} /></span>}
        <span style={{ flex: 1, minWidth: 0 }}>
          {vehicle ? (
            <React.Fragment>
              <span style={{ display: 'block', fontFamily: T.display, fontSize: 14.5, fontWeight: 600, color: P.paper, lineHeight: 1.15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{vehicle.year} {vehicle.make} {vehicle.model}</span>
              <VehSub v={vehicle} />
            </React.Fragment>
          ) : (
            <span style={{ display: 'block', fontFamily: T.body, fontSize: 12.5, color: P.mute }}>Select a vehicle</span>
          )}
        </span>
        <span style={{ fontFamily: T.mono, fontSize: 9, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: P.gold, flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          {vehicle ? 'Change' : 'Assign'}
          <Icon name="arrow" size={13} color={P.gold} strokeWidth={2} />
        </span>
      </button>
    </div>
  );
}

// ── the simplified assignment sheet ─────────────────────────────────────
// Props:
//   vehicles       searchable pool (real vehicles ∪ roster)
//   currentId      the vehicle currently assigned, or null
//   suggestedId    the AI's suggestion (usually === currentId at first review)
//   reasoning      [why, learned] strings — shown only under the AI suggestion
//   title          sheet eyebrow, e.g. "CHANGE ASSIGNMENT" / "ASSIGN VEHICLE"
//   subtitle       one line describing what's being assigned (submission title)
//   confirmLabel   primary button label when a change is pending
function VehicleAssignSheet({ vehicles, currentId, suggestedId, reasoning, title = 'ASSIGN VEHICLE', subtitle, confirmLabel = 'Assign', onAssign, onClose }) {
  const [picked, setPicked] = useAvA(currentId || null);
  const [query, setQuery] = useAvA('');

  const pool = vehiclePool(vehicles);
  const byId = {}; pool.forEach(v => { byId[v.id] = v; });
  const current = currentId ? byId[currentId] : null;
  const showReasoning = !!(reasoning && reasoning.length) && currentId && currentId === suggestedId && picked === currentId;

  const results = query.trim() ? searchVehicles(pool, query) : [];
  const RESULT_CAP = 24;
  const shownResults = results.slice(0, RESULT_CAP);
  const moreResults = Math.max(0, results.length - RESULT_CAP);

  const recents = (typeof COLLECTION_RECENT_IDS !== 'undefined' ? COLLECTION_RECENT_IDS : [])
    .map(id => byId[id]).filter(Boolean).filter(v => v.id !== currentId).slice(0, 4);

  const changed = picked !== currentId;
  const primaryEnabled = !!picked && changed;

  const clearSearch = () => setQuery('');
  const searchField = (
    <div style={{ position: 'relative' }}>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search by name, nickname, VIN, or project"
        style={{
          width: '100%', height: 44, boxSizing: 'border-box', background: P.ink,
          border: `1px solid ${query.trim() ? P.gold : P.slate}`, outline: 'none', color: P.paper,
          fontFamily: T.body, fontSize: 12.5, padding: '0 36px 0 14px',
        }} />
      {query.trim() && (
        <button onClick={clearSearch} aria-label="Clear search" style={{ position: 'absolute', right: 6, top: 0, bottom: 0, width: 30, background: 'transparent', border: 'none', color: P.mute, cursor: 'pointer', fontFamily: T.mono, fontSize: 15 }}>×</button>
      )}
    </div>
  );

  const node = (
    <div style={{ position: 'absolute', inset: 0, zIndex: 97 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(10,10,11,0.82)', backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)', animation: 'sheetFade .2s ease' }} />
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '86%', background: P.graphite, color: P.paper, borderTop: `1px solid ${P.gold}`, display: 'flex', flexDirection: 'column', animation: 'sheetIn .25s cubic-bezier(.2,.7,.3,1)' }}>
        {/* header */}
        <div style={{ padding: '14px 22px 12px', flex: '0 0 auto', borderBottom: `1px solid ${P.slate}` }}>
          <div style={{ width: 40, height: 4, background: P.slate, margin: '0 auto 14px' }} />
          <Eyebrow color={P.gold}>{title}</Eyebrow>
          {subtitle && <div style={{ fontFamily: T.body, fontSize: 13.5, color: P.paper, marginTop: 7, lineHeight: 1.35 }}>{subtitle}</div>}
        </div>

        <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', padding: '16px 22px 8px' }}>
          {/* ── current assignment, when one exists ── */}
          {current && (
            <React.Fragment>
              <AllocSectionLabel>CURRENT ASSIGNMENT</AllocSectionLabel>
              <div style={{ border: `1px solid ${P.slate}`, marginBottom: 18 }}>
                <SelectRow
                  selected={picked === current.id}
                  onClick={() => setPicked(current.id)}
                  last
                  thumb={<MarqueThumb v={current} />}
                  title={`${current.year} ${current.make} ${current.model}`}
                  sub={<VehSub v={current} />}
                />
                {showReasoning && (
                  <div style={{ background: '#2C2A25', borderTop: `1px solid ${P.slate}`, padding: '13px 14px 14px', boxShadow: 'inset 0 8px 10px -8px rgba(0,0,0,0.75)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 10 }}>
                      <Icon name="spark" size={12} color={P.gold} strokeWidth={2} />
                      <RcMono size={8} color={P.gold} tracking="0.18em">MATCH REASONING</RcMono>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                      {reasoning.filter(Boolean).map((t, i) => (
                        <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={P.gold} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}><path d="M20 6L9 17l-5-5" /></svg>
                          <div style={{ fontFamily: T.body, fontSize: 12, color: P.bone, lineHeight: 1.45 }}>{t.replace(/[“”"]/g, '')}</div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </React.Fragment>
          )}

          {/* ── search + results — the only way to pick a different vehicle ── */}
          <AllocSectionLabel>{current ? 'SELECT A DIFFERENT VEHICLE' : 'SEARCH COLLECTION'}</AllocSectionLabel>
          <div style={{ marginBottom: query.trim() ? 18 : (recents.length ? 12 : 4) }}>{searchField}</div>

          {query.trim() ? (
            <div>
              <AllocSectionLabel>{`SEARCH RESULTS · ${results.length}`}</AllocSectionLabel>
              {results.length === 0 ? (
                <div style={{ padding: '16px 13px', textAlign: 'center', border: `1px solid ${P.slate}` }}>
                  <RcMono size={9} color={P.mute} tracking="0.04em" style={{ textTransform: 'none', letterSpacing: '0.02em' }}>No vehicle matches “{query.trim()}”</RcMono>
                </div>
              ) : (
                <div style={{ border: `1px solid ${P.slate}` }}>
                  {shownResults.map((v, i) => (
                    <SelectRow key={v.id}
                      selected={picked === v.id}
                      onClick={() => setPicked(v.id)}
                      last={i === shownResults.length - 1 && moreResults === 0}
                      thumb={<MarqueThumb v={v} />}
                      title={`${v.year} ${v.make} ${v.model}`}
                      sub={<VehSub v={v} />} />
                  ))}
                  {moreResults > 0 && (
                    <div style={{ padding: '9px 13px', borderTop: `1px solid ${P.slate}` }}><RcMono size={8} color={P.mute} tracking="0.04em" style={{ textTransform: 'none', letterSpacing: '0.02em' }}>+ {moreResults} more — refine your search</RcMono></div>
                  )}
                </div>
              )}
            </div>
          ) : recents.length > 0 && (
            <div>
              <AllocSectionLabel>RECENT</AllocSectionLabel>
              <div style={{ border: `1px solid ${P.slate}` }}>
                {recents.map((v, i) => (
                  <SelectRow key={v.id}
                    selected={picked === v.id}
                    onClick={() => setPicked(v.id)}
                    last={i === recents.length - 1}
                    thumb={<MarqueThumb v={v} />}
                    title={`${v.year} ${v.make} ${v.model}`}
                    sub={<VehSub v={v} />} />
                ))}
              </div>
            </div>
          )}
        </div>

        <div style={{ padding: '10px 22px 30px', flex: '0 0 auto', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, borderTop: `1px solid ${P.slate}` }}>
          <button onClick={onClose} style={{ height: 48, background: 'transparent', border: `1px solid ${P.slate}`, color: P.paper, fontFamily: T.mono, fontSize: 10, fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer' }}>Cancel</button>
          <button onClick={() => primaryEnabled && (onAssign(picked), onClose())} disabled={!primaryEnabled} style={{
            height: 48, background: primaryEnabled ? P.gold : 'transparent', border: `1px solid ${primaryEnabled ? P.gold : P.slate}`,
            color: primaryEnabled ? P.ink : P.mute, fontFamily: T.mono, fontSize: 10, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase',
            cursor: primaryEnabled ? 'pointer' : 'not-allowed', opacity: primaryEnabled ? 1 : 0.55,
          }}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
  const stage = (typeof document !== 'undefined') ? (document.getElementById('proto-stage') || document.getElementById('contrib-stage')) : null;
  return stage ? ReactDOM.createPortal(node, stage) : node;
}

Object.assign(window, { VehicleAssignRow, VehicleAssignSheet });
