// SCREEN 03 — Ownership & Provenance
// Premium ownership history experience. Emotionally valuable.

const { useState: useS, useEffect: useE } = React;

// Module-level scratch — survives screen switches so the entries the user
// adds during the session don't vanish when they hop to another tab.
let _ownershipExtras = [];

// ─────────────────────────────────────────────────────────────────────
// ADD OWNERSHIP EVENT — bottom sheet
// ─────────────────────────────────────────────────────────────────────

function AddOwnershipSheet({ onClose, onSave }) {
  const [kind, setKind] = useS('sell');          // 'buy' | 'sell' | 'transfer'
  const [owner, setOwner] = useS('');
  const [place, setPlace] = useS('');
  const [date, setDate] = useS('');
  const [price, setPrice] = useS('');
  const [source, setSource] = useS('Auction');
  const [note, setNote] = useS('');

  // Lock body scroll & enable Esc-to-close
  useE(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const Field = ({ label, value, onChange, placeholder, suffix, mono }) => (
    <div>
      <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', gap: 8,
      }}>
        <input value={value} onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: P.paper, fontFamily: mono ? T.mono : T.body, fontSize: 13,
            letterSpacing: mono ? '0.04em' : 0,
          }} />
        {suffix && <span style={{ fontFamily: T.mono, fontSize: 10, color: P.mute }}>{suffix}</span>}
      </div>
    </div>
  );

  const KindPick = () => (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
      border: `1px solid ${P.slate}`, marginBottom: 18,
    }}>
      {[
        ['buy',      'Buy',      'You acquired the car'],
        ['sell',     'Sell',     'You sold the car'],
        ['transfer', 'Transfer', 'Historical handoff'],
      ].map(([id, label, hint], i) => {
        const on = kind === id;
        return (
          <button key={id} onClick={() => setKind(id)} style={{
            background: on ? P.paper : 'transparent',
            color: on ? P.ink : P.paper,
            border: 'none', cursor: 'pointer',
            padding: '12px 8px',
            borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none',
            fontFamily: T.mono, fontSize: 10, fontWeight: 600,
            letterSpacing: '0.18em', textTransform: 'uppercase',
          }}>{label}</button>
        );
      })}
    </div>
  );

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 70,
      display: 'flex', alignItems: 'flex-end',
      animation: 'sheetIn .25s cubic-bezier(.2,.7,.3,1)',
    }}>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0,
        background: 'rgba(10,10,11,0.78)',
        backdropFilter: 'blur(2px)',
        WebkitBackdropFilter: 'blur(2px)',
      }} />

      {/* Sheet */}
      <div className="proto-scroll" style={{
        position: 'relative', width: '100%', maxHeight: '88%',
        background: P.graphite, color: P.paper,
        borderTop: `1px solid ${P.gold}`,
        padding: '14px 22px 90px',
        overflow: 'auto',
      }}>
        {/* Drag handle */}
        <div style={{
          width: 40, height: 4, background: P.slate, margin: '0 auto 14px',
        }} />

        {/* Header */}
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          marginBottom: 18,
        }}>
          <div>
            <Eyebrow color={P.gold}>OWNERSHIP · NEW ENTRY</Eyebrow>
            <div style={{
              fontFamily: T.display, fontSize: 24, fontWeight: 700,
              color: P.paper, marginTop: 6, letterSpacing: '-0.015em',
            }}>LOG AN EVENT</div>
          </div>
          <button onClick={onClose} style={{
            background: 'transparent', border: `1px solid ${P.slate}`,
            color: P.paper, padding: '6px 10px', cursor: 'pointer',
            fontFamily: T.mono, fontSize: 9, fontWeight: 600,
            letterSpacing: '0.2em', textTransform: 'uppercase',
          }}>CLOSE</button>
        </div>

        <KindPick />

        <div style={{ display: 'grid', gap: 14, marginBottom: 18 }}>
          <Field
            label={kind === 'buy' ? 'Seller' : kind === 'sell' ? 'Buyer' : 'New owner'}
            value={owner} onChange={setOwner}
            placeholder={kind === 'buy' ? 'Who you bought from' : kind === 'sell' ? 'Who you sold to' : 'Name'}
          />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Field
              label="Date"
              value={date} onChange={setDate}
              placeholder="MMM YYYY" mono
            />
            <Field
              label="Location"
              value={place} onChange={setPlace}
              placeholder="City, State"
            />
          </div>

          {kind !== 'transfer' && (
            <>
              <Field
                label={kind === 'buy' ? 'Purchase price (USD)' : 'Sale price (USD)'}
                value={price} onChange={setPrice}
                placeholder="0" suffix="USD" mono
              />
              {/* Source segmented */}
              <div>
                <div style={{
                  fontFamily: T.mono, fontSize: 9, letterSpacing: '0.2em',
                  textTransform: 'uppercase', color: P.mute, marginBottom: 6,
                }}>Source</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {['Auction', 'Dealer', 'Private', 'Broker'].map(s => {
                    const on = source === s;
                    return (
                      <button key={s} onClick={() => setSource(s)} 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.18em', textTransform: 'uppercase',
                        cursor: 'pointer',
                      }}>{s}</button>
                    );
                  })}
                </div>
              </div>
            </>
          )}

          <div>
            <div style={{
              fontFamily: T.mono, fontSize: 9, letterSpacing: '0.2em',
              textTransform: 'uppercase', color: P.mute, marginBottom: 6,
            }}>Notes</div>
            <textarea value={note} onChange={(e) => setNote(e.target.value)}
              placeholder="Anything worth remembering — condition at sale, story, witnesses…"
              rows={3}
              style={{
                width: '100%', resize: 'none',
                background: P.ink, color: P.paper,
                border: `1px solid ${P.slate}`, padding: 12,
                fontFamily: T.body, fontSize: 13, lineHeight: 1.5,
                outline: 'none',
              }} />
          </div>
        </div>

        {/* Save row */}
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1.6fr', gap: 8,
        }}>
          <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.2em', textTransform: 'uppercase', cursor: 'pointer',
          }}>CANCEL</button>
          <button
            onClick={() => { onSave({ kind, owner, place, date, price, source, note }); onClose(); }}
            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',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
            <Icon name="certificate" size={14} color={P.ink} strokeWidth={1.8} />
            {kind === 'buy' ? 'LOG PURCHASE' : kind === 'sell' ? 'LOG SALE' : 'SAVE TRANSFER'}
          </button>
        </div>
      </div>

      <style>{`@keyframes sheetIn { from { transform: translateY(20px); opacity: 0 } to { transform: none; opacity: 1 } }`}</style>
    </div>
  );
}

function ScreenProvenance() {
  const v = VEHICLE;
  const [sheetOpen, setSheetOpen] = useS(false);
  const [, force] = useS(0);

  // Compose chain: extras first (most recent), then base
  const chain = [..._ownershipExtras, ...v.ownership_chain];

  const handleSave = (entry) => {
    // Translate the form into a chain row at the top
    const owner =
      entry.kind === 'buy'      ? `Acquired from ${entry.owner || '—'}`
    : entry.kind === 'sell'     ? `Sold to ${entry.owner || '—'}`
    :                              entry.owner || 'Transfer';
    _ownershipExtras = [{
      from: entry.date || 'today',
      to: entry.kind === 'sell' ? 'present' : '—',
      owner,
      where: entry.place || '—',
      note: entry.note ||
            (entry.kind === 'sell' ? `Sale via ${entry.source}` :
             entry.kind === 'buy'  ? `Purchase via ${entry.source}` : 'Historical handoff'),
      kind: entry.kind === 'sell' ? 'private' : entry.kind === 'buy' ? 'self' : 'private',
      isNew: true,
    }, ..._ownershipExtras];
    force(x => x + 1);
  };

  return (
    <div className="proto-screen" style={{ background: P.ink, color: P.paper }}>

      <ScreenIntro
        eyebrow="OWNERSHIP · COLLECTOR ARCHIVE"
        title="EVERY HAND IT'S PASSED THROUGH"
        sub="A car of consequence is the sum of its owners. Each entry is a verified handoff in the unbroken chain."
        right={
          <div style={{ textAlign: 'right' }}>
            <div style={{
              fontFamily: T.display, fontSize: 32, fontWeight: 700,
              color: P.gold, letterSpacing: '-0.02em',
            }}>{chain.length}</div>
            <Eyebrow color={P.mute}>OWNERS</Eyebrow>
          </div>
        }
      />

      {/* Authenticity strip */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{
          background: P.graphite, borderTop: `1px solid ${P.gold}`, borderBottom: `1px solid ${P.gold}`,
          padding: '14px 16px',
          display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12,
        }}>
          {[
            ['MATCHING VIN',   v.provenance.matchingVin ? '✓ VERIFIED' : '—'],
            ['ENGINE',         v.provenance.originalEngine ? '✓ ORIGINAL' : 'REPLACED'],
            ['GEARBOX',        v.provenance.originalTrans ? '✓ ORIGINAL' : 'REPLACED'],
          ].map(([k, val]) => (
            <div key={k}>
              <Eyebrow color={P.mute}>{k}</Eyebrow>
              <div style={{
                fontFamily: T.mono, fontSize: 10, fontWeight: 600,
                letterSpacing: '0.14em', color: P.gold, marginTop: 4,
              }}>{val}</div>
            </div>
          ))}
        </div>
      </div>

      <RowRule>OWNERSHIP CHAIN · 1973 — PRESENT</RowRule>

      {/* Chain — visual timeline */}
      <div style={{ padding: '18px 22px 8px', position: 'relative' }}>
        <div style={{
          position: 'absolute', left: 38, top: 16, bottom: 16,
          width: 1, background: P.slate,
        }} />

        {chain.map((o, i) => {
          const kindLabel = {
            factory: 'FACTORY',
            private: 'PRIVATE',
            collection: 'COLLECTION',
            self: 'CURRENT',
          }[o.kind];
          const isYou = o.current;
          const isNew = o.isNew;

          return (
            <div key={i} style={{
              position: 'relative', paddingLeft: 52, paddingBottom: 22,
            }}>
              {/* Marker */}
              <div style={{
                position: 'absolute', left: 28, top: 4,
                width: 21, height: 21,
                border: `1.5px solid ${isYou || isNew ? P.gold : P.slate}`,
                background: isYou ? P.gold : isNew ? P.ink : P.ink,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <div style={{
                  fontFamily: T.display, fontSize: 11, fontWeight: 700,
                  color: isYou ? P.ink : P.gold,
                }}>{(chain.length - i).toString().padStart(2, '0')}</div>
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <Eyebrow color={isYou || isNew ? P.gold : P.mute}>{isNew ? 'NEW · ' + kindLabel : kindLabel}</Eyebrow>
                <div style={{
                  fontFamily: T.mono, fontSize: 9, color: P.mute,
                  letterSpacing: '0.18em', textTransform: 'uppercase',
                }}>{o.from} — {o.to}</div>
              </div>

              <div style={{
                fontFamily: T.display, fontSize: 17, fontWeight: 600,
                color: P.paper, marginTop: 6, letterSpacing: '-0.005em',
                lineHeight: 1.1,
              }}>{o.owner}</div>
              <div style={{
                fontFamily: T.mono, fontSize: 10, color: P.gold,
                letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 3,
              }}>{o.where.toUpperCase()}</div>
              <div style={{
                fontFamily: T.body, fontSize: 11, color: P.bone, marginTop: 6,
                lineHeight: 1.45,
              }}>{o.note}</div>
            </div>
          );
        })}

        {/* Add ownership event */}
        <div style={{ position: 'relative', paddingLeft: 52, paddingTop: 6 }}>
          <div style={{
            position: 'absolute', left: 28, top: 12,
            width: 21, height: 21,
            border: `1px dashed ${P.gold}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: P.gold, fontFamily: T.display, fontSize: 14, fontWeight: 700,
          }}>+</div>
          <button onClick={() => setSheetOpen(true)} style={{
            width: '100%', textAlign: 'left',
            background: 'transparent',
            border: `1px dashed ${P.gold}`,
            color: P.gold,
            padding: '12px 14px',
            fontFamily: T.mono, fontSize: 10, fontWeight: 600,
            letterSpacing: '0.2em', textTransform: 'uppercase',
            cursor: 'pointer',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <span>ADD OWNERSHIP EVENT</span>
            <span style={{ color: P.mute, fontFamily: T.body, textTransform: 'none', letterSpacing: 0, fontSize: 10 }}>buy · sell · transfer</span>
          </button>
        </div>
      </div>

      {/* Awards */}
      <div style={{ padding: '14px 0 4px' }}>
        <RowRule>CONCOURS & AWARDS</RowRule>
      </div>
      <div style={{ padding: '14px 22px 8px' }}>
        {v.provenance.awards.map((a, i) => (
          <InkCard key={i} accent padding={14} style={{
            marginBottom: 6,
            display: 'grid', gridTemplateColumns: '36px 1fr 60px',
            gap: 14, alignItems: 'center',
          }}>
            <Icon name="certificate" size={22} color={P.gold} strokeWidth={1.6} />
            <div>
              <div style={{
                fontFamily: T.display, fontSize: 14, fontWeight: 600,
                color: P.paper, letterSpacing: '-0.005em',
              }}>{a.event}</div>
              <div style={{
                fontFamily: T.mono, fontSize: 9, color: P.mute,
                letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 3,
              }}>{a.placement.toUpperCase()}</div>
            </div>
            <div style={{
              fontFamily: T.display, fontSize: 22, fontWeight: 700,
              color: P.gold, letterSpacing: '-0.02em', textAlign: 'right',
            }}>{a.year}</div>
          </InkCard>
        ))}
      </div>

      {/* Historical significance */}
      <div style={{ padding: '14px 0 4px' }}>
        <RowRule>HISTORICAL SIGNIFICANCE</RowRule>
      </div>
      <div style={{ padding: '14px 22px 8px' }}>
        {v.provenance.significance.map((s, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '20px 1fr', gap: 12,
            padding: '10px 0',
            borderBottom: i < v.provenance.significance.length - 1 ? `1px solid ${P.graphite}` : 'none',
          }}>
            <div style={{
              fontFamily: T.display, fontSize: 12, fontWeight: 700,
              color: P.gold, letterSpacing: '-0.01em',
            }}>0{i + 1}</div>
            <div style={{
              fontFamily: T.body, fontSize: 13, lineHeight: 1.5,
              color: P.paper,
            }}>{s}</div>
          </div>
        ))}
      </div>

      {/* Factory documentation */}
      <div style={{ padding: '14px 0 4px' }}>
        <RowRule>FACTORY DOCUMENTATION</RowRule>
      </div>
      <div style={{ padding: '14px 22px 8px' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {v.provenance.docs.map(d => (
            <span key={d} style={{
              padding: '7px 11px',
              border: `1px solid ${P.slate}`,
              fontFamily: T.mono, fontSize: 9, fontWeight: 500,
              letterSpacing: '0.14em', textTransform: 'uppercase',
              color: P.paper,
              display: 'inline-flex', gap: 6, alignItems: 'center',
            }}>
              <Icon name="certificate" size={12} color={P.gold} strokeWidth={1.5} />
              {d}
            </span>
          ))}
        </div>
        <div style={{
          marginTop: 14, fontFamily: T.mono, fontSize: 9, color: P.mute,
          letterSpacing: '0.16em', textTransform: 'uppercase',
        }}>
          All documents archived in Vault →
        </div>
      </div>

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

      {sheetOpen && (
        <AddOwnershipSheet
          onClose={() => setSheetOpen(false)}
          onSave={handleSave}
        />
      )}
    </div>
  );
}

Object.assign(window, { ScreenProvenance });
