// ─────────────────────────────────────────────────────────────────────
// PHOTO RECORD — full-page, deep-linkable archive record for one photo.
// Replaces the modal. Each photo is a first-class record with its own URL,
// browser-back support, sharing, prev/next + swipe, linked records and
// related photos.
// ─────────────────────────────────────────────────────────────────────

function VRRecordMeta({ label, value, accent, onClick }) {
  return (
    <div onClick={onClick} style={{
      padding: '12px 0', borderBottom: `1px solid ${P.graphite}`,
      display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'baseline',
      cursor: onClick ? 'pointer' : 'default'
    }}>
      <span style={{
        fontFamily: T.mono, fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase',
        color: P.mute, whiteSpace: 'nowrap'
      }}>{label}</span>
      <span style={{
        fontFamily: T.body, fontSize: 12.5, color: accent || P.paper, textAlign: 'right', lineHeight: 1.4
      }}>{value}</span>
    </div>);

}

// A linked-record row (document / maintenance / appraisal).
function VRLinkRow({ icon, kind, title, meta }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '34px 1fr auto', gap: 12, alignItems: 'center',
      padding: '12px 0', borderBottom: `1px solid ${P.graphite}`
    }}>
      <div style={{
        width: 34, height: 34, border: `1px solid ${P.slate}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center'
      }}>
        <Icon name={icon} size={15} color={P.gold} strokeWidth={1.5} />
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: P.gold }}>{kind}</div>
        <div style={{ fontFamily: T.display, fontSize: 13, fontWeight: 600, color: P.paper, marginTop: 2, letterSpacing: '-0.005em' }}>{title}</div>
        <div style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.mute, marginTop: 2 }}>{meta}</div>
      </div>
      <Icon name="arrow" size={15} color={P.mute} strokeWidth={1.4} />
    </div>);

}

function VRPhotoRecord({ vehicle, photo, index, total, related, onPrev, onNext, onClose, onShare, onJumpTo, onDelete, shareState }) {
  const v = vehicle;
  const touchX = React.useRef(null);
  const [menu, setMenu] = React.useState(false);
  const eventName = photo.tags && photo.tags[1] ? photo.tags[1] : 'Documentation';

  // Resolve a few authentic cross-links from the vehicle record.
  const doc = (v.documents || []).flatMap((c) => c.items.map((i) => ({ ...i, category: c.category }))).
  find((i) => i.category && (i.category.toLowerCase().includes('service') || i.archival)) || null;
  const svc = (v.service || [])[0] || null;
  const appr = v.value && v.value.appraisals && v.value.appraisals[0] || null;

  const onTouchStart = (e) => {touchX.current = e.touches[0].clientX;};
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    if (dx < -45 && index < total - 1) onNext();else
    if (dx > 45 && index > 0) onPrev();
    touchX.current = null;
  };

  const NavBtn = ({ dir, disabled }) =>
  <button onClick={dir === 'prev' ? onPrev : onNext} disabled={disabled} style={{
    position: 'absolute', top: '50%', transform: 'translateY(-50%)',
    [dir === 'prev' ? 'left' : 'right']: 10, zIndex: 3,
    width: 38, height: 38, borderRadius: 999, cursor: disabled ? 'default' : 'pointer',
    background: 'rgba(10,10,11,0.6)', border: `1px solid ${disabled ? 'transparent' : 'rgba(244,239,230,0.25)'}`,
    color: disabled ? 'rgba(244,239,230,0.25)' : P.paper, backdropFilter: 'blur(4px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center'
  }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        {dir === 'prev' ? <path d="M15 18l-6-6 6-6" /> : <path d="M9 18l6-6-6-6" />}
      </svg>
    </button>;


  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 95, background: P.ink, color: P.paper,
      display: 'flex', flexDirection: 'column',
      animation: 'recordIn .26s cubic-bezier(.2,.7,.3,1)'
    }}>
      {/* Top bar */}
      <div style={{
        flex: '0 0 auto', padding: '10px 18px 12px', background: P.ink,
        borderBottom: `1px solid ${P.graphite}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12
      }}>
        <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, textAlign: 'left', minWidth: 0 }}>
          <div style={{ fontFamily: T.display, fontWeight: 600, fontSize: 14, letterSpacing: '0.02em', color: P.paper, lineHeight: 1.1 }}>PHOTO RECORD</div>
          <div style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.24em', textTransform: 'uppercase', color: P.gold, marginTop: 3 }}>
            {index + 1} / {total} · {photo.area}
          </div>
        </div>
        <button onClick={() => setMenu((m) => !m)} aria-label="More" style={{
          background: 'transparent', border: 'none', padding: 6, cursor: 'pointer',
          color: P.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <circle cx="12" cy="5" r="1.2" /><circle cx="12" cy="12" r="1.2" /><circle cx="12" cy="19" r="1.2" />
          </svg>
        </button>
      </div>

      {/* More — mobile action sheet */}
      {menu &&
      <ActionSheet
        eyebrow="PHOTO RECORD"
        title={photo.area.toUpperCase()}
        onClose={() => setMenu(false)}
        items={[
        { label: 'Edit record', icon: 'wrench', action: () => {} },
        { label: 'Share record', icon: 'share', action: () => onShare && onShare() },
        { label: 'Delete photo', icon: 'flag', danger: true, action: () => onDelete && onDelete(photo) }]
        } />
      }

      {/* Scrolling record body */}
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto' }}>
        {/* Full-res image */}
        <div onTouchStart={onTouchStart} onTouchEnd={onTouchEnd} style={{
          position: 'relative', width: '100%', aspectRatio: '4 / 3',
          background: photo.src ? '#000' : `repeating-linear-gradient(135deg, ${P.graphite} 0 14px, rgba(255,255,255,0.045) 14px 15px)`
        }}>
          {photo.src ?
          <img src={photo.src} alt={photo.area} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain' }} /> :
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: T.mono, fontSize: 10, letterSpacing: '0.2em', color: P.mute, textTransform: 'uppercase' }}>▣ {photo.area}</div>}
          <NavBtn dir="prev" disabled={index <= 0} />
          <NavBtn dir="next" disabled={index >= total - 1} />
          {photo._new &&
          <div style={{ position: 'absolute', top: 10, left: 10, fontFamily: T.mono, fontSize: 8, fontWeight: 700, letterSpacing: '0.14em', color: P.ink, background: P.gold, padding: '3px 6px', textTransform: 'uppercase' }}>NEW</div>
          }
        </div>

        <div style={{ padding: '20px 22px 40px' }}>
          {/* Record header */}
          <Eyebrow color={P.gold}>{photo.area.toUpperCase()}</Eyebrow>
          <div style={{ fontFamily: T.display, fontSize: 26, fontWeight: 700, color: P.paper, marginTop: 6, letterSpacing: '-0.015em', lineHeight: 1 }}>{eventName.toUpperCase()}</div>
          <div style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: P.mute, marginTop: 8 }}>
            {v.year} {v.make} {v.model} · REC {String(photo.id).slice(-6).toUpperCase()}
          </div>

          {/* Condition + damage */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '16px 0 0' }}>
            <VRConditionDot condition={photo.condition} size={9} />
            <span style={{ fontFamily: T.mono, fontSize: 10, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: vrConditionColor(photo.condition) }}>{photo.condition}</span>
          </div>
          {photo.damage &&
          <div style={{ marginTop: 12, padding: '10px 12px', background: 'rgba(122,36,24,0.18)', borderLeft: `2px solid ${P.signal}` }}>
              <span style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.16em', color: P.signal, textTransform: 'uppercase' }}>DAMAGE INDICATOR</span>
              <div style={{ marginTop: 4, fontFamily: T.body, fontSize: 12, color: P.paper }}>{photo.damage}</div>
            </div>
          }

          {/* Metadata */}
          <div style={{ marginTop: 20 }}>
            <RuleLabel color={P.slate}>RECORD METADATA</RuleLabel>
            <div style={{ marginTop: 8 }}>
              <VRRecordMeta label="Event" value={eventName} accent={P.gold} />
              <VRRecordMeta label="Date / Time" value={photo.time} />
              <VRRecordMeta label="Photographer" value={photo.photographer} />
              <VRRecordMeta label="Odometer" value={fmtMiles(photo.odometer || 0)} />
              <VRRecordMeta label="Vehicle Area" value={photo.area} />
              <VRRecordMeta label="Condition" value={photo.condition} accent={vrConditionColor(photo.condition)} />
              <VRRecordMeta label="Restoration Stage" value={photo.restoration || 'N/A'} />
            </div>
          </div>

          {/* Notes */}
          {photo.note &&
          <div style={{ marginTop: 22 }}>
              <RuleLabel color={P.slate}>NOTES</RuleLabel>
              <div style={{ fontFamily: T.body, fontSize: 13, color: P.paper, lineHeight: 1.55, marginTop: 10 }}>{photo.note}</div>
            </div>
          }

          {/* Tags */}
          <div style={{ marginTop: 22 }}>
            <RuleLabel color={P.slate}>TAGS</RuleLabel>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>
              {(photo.tags || []).map((t) =>
              <span key={t} style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: P.mute, border: `1px solid ${P.slate}`, padding: '5px 8px' }}>{t}</span>
              )}
            </div>
          </div>

          {/* Linked records */}
          <div style={{ marginTop: 24 }}>
            <RuleLabel color={P.slate}>LINKED RECORDS</RuleLabel>
            <div style={{ marginTop: 6 }}>
              {doc && <VRLinkRow icon="bookmark" kind="DOCUMENT" title={doc.name} meta={`${doc.date} · ${doc.pages} ${doc.kind === 'image' ? 'IMG' : 'PG'}`} />}
              {svc && <VRLinkRow icon="wrench" kind="MAINTENANCE" title={svc.item} meta={`${svc.date} · ${svc.vendor}`} />}
              {appr && <VRLinkRow icon="hammer" kind="APPRAISAL" title={`${appr.source}`} meta={`${appr.date} · ${fmtMoney(appr.value, { compact: true })}`} />}
              {!doc && !svc && !appr &&
              <div style={{ padding: '14px 0', fontFamily: T.mono, fontSize: 9, color: P.mute, letterSpacing: '0.14em', textTransform: 'uppercase' }}>No linked records yet</div>
              }
            </div>
            <button style={{
              width: '100%', marginTop: 10, padding: '11px 0', background: 'transparent',
              border: `1px dashed ${P.slate}`, color: P.mute, fontFamily: T.mono, fontSize: 9,
              fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer'
            }}>+ LINK A RECORD</button>
          </div>

          {/* Related photos */}
          {related && related.length > 0 &&
          <div style={{ marginTop: 24 }}>
              <RuleLabel color={P.slate}>RELATED PHOTOS</RuleLabel>
              <div className="proto-scroll" style={{ display: 'flex', gap: 6, overflowX: 'auto', marginTop: 12, paddingBottom: 4 }}>
                {related.map((rp) =>
              <button key={rp.id} onClick={() => onJumpTo(rp)} style={{
                flex: '0 0 auto', width: 96, aspectRatio: '1 / 1', padding: 0, border: 'none', cursor: 'pointer',
                position: 'relative', overflow: 'hidden',
                background: rp.src ? '#000' : `repeating-linear-gradient(135deg, ${P.graphite} 0 10px, rgba(255,255,255,0.045) 10px 11px)`
              }}>
                    {rp.src && <img src={rp.src} alt={rp.area} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />}
                    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(10,10,11,0) 50%, rgba(10,10,11,0.8) 100%)' }} />
                    <div style={{ position: 'absolute', left: 6, right: 6, bottom: 5, fontFamily: T.mono, fontSize: 7, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.paper, textAlign: 'left' }}>{rp.area}</div>
                  </button>
              )}
              </div>
            </div>
          }

          {/* Share actions */}
          <div style={{ fontFamily: T.mono, fontSize: 8, color: P.mute, letterSpacing: '0.12em', textTransform: 'uppercase', textAlign: 'center', marginTop: 28, lineHeight: 1.7 }}>
            SHAREABLE LINK · APPRAISER · BROKER · INSURER<br />SWIPE OR USE ◂ ▸ TO BROWSE
          </div>
        </div>
      </div>
    </div>);

}

Object.assign(window, { VRPhotoRecord, VRRecordMeta, VRLinkRow });