// ─────────────────────────────────────────────────────────────────────
// GALLERY PARTS — tiles, sheets, cards for the Visual Record
// Shared building blocks for ScreenGallery. Exported to window.
// ─────────────────────────────────────────────────────────────────────

// Small condition dot.
function VRConditionDot({ condition, size = 7 }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: size,
      background: vrConditionColor(condition), flexShrink: 0,
      display: 'inline-block',
      boxShadow: '0 0 0 2px rgba(10,10,11,0.6)',
    }} />
  );
}

// A single photo tile — real image or striped placeholder, with area label
// and condition dot. Tap opens the detail sheet. In manage mode a delete
// control appears.
function VRPhotoTile({ photo, onOpen, showArea = true, manage = false, onDelete }) {
  return (
    <button onClick={() => manage ? null : onOpen(photo)} style={{
      position: 'relative', aspectRatio: '1 / 1', width: '100%',
      padding: 0, border: 'none', cursor: manage ? 'default' : 'pointer', overflow: 'hidden',
      background: photo.src ? P.ink
        : `repeating-linear-gradient(135deg, ${P.graphite} 0 12px, rgba(255,255,255,0.045) 12px 13px)`,
      display: 'block',
    }}>
      {photo.src && (
        <img src={photo.src} alt={photo.area} style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover', display: 'block',
        }} />
      )}
      {/* legibility scrim */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(to bottom, rgba(10,10,11,0) 45%, rgba(10,10,11,0.82) 100%)',
      }} />
      {/* condition dot */}
      <div style={{ position: 'absolute', top: 7, left: 7, display: 'flex', gap: 5, alignItems: 'center' }}>
        <VRConditionDot condition={photo.condition} />
        {photo.damage && (
          <span style={{
            fontFamily: T.mono, fontSize: 7, fontWeight: 700, letterSpacing: '0.12em',
            color: P.paper, background: P.signal, padding: '2px 4px', textTransform: 'uppercase',
          }}>!</span>
        )}
      </div>
      {!manage && photo._new && (
        <div style={{
          position: 'absolute', top: 7, right: 7,
          fontFamily: T.mono, fontSize: 7, fontWeight: 700, letterSpacing: '0.12em',
          color: P.ink, background: P.gold, padding: '2px 5px', textTransform: 'uppercase',
        }}>NEW</div>
      )}
      {manage && (
        <span role="button" onClick={(e) => { e.stopPropagation(); onDelete && onDelete(photo); }} style={{
          position: 'absolute', top: 5, right: 5, zIndex: 2,
          width: 24, height: 24, borderRadius: 999, cursor: 'pointer',
          background: P.signal, color: P.paper,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: T.mono, fontSize: 15, lineHeight: 1,
          boxShadow: '0 2px 6px rgba(0,0,0,0.5)',
        }}>×</span>
      )}
      {showArea && (
        <div style={{
          position: 'absolute', left: 7, right: 7, bottom: 6,
          fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.1em',
          textTransform: 'uppercase', color: P.paper, textAlign: 'left',
          lineHeight: 1.2, textShadow: '0 1px 2px rgba(0,0,0,0.6)',
        }}>{photo.area}</div>
      )}
    </button>
  );
}

// Event card — a documentation session. Collapsed shows a thumbnail strip;
// expanded shows the full grid with add / manage (delete) controls.
function VREventCard({ event, expanded, onToggle, onOpenPhoto, onAddToEvent, onDeletePhoto }) {
  const [manage, setManage] = React.useState(false);
  // Collapsed strip: up to 4 boxes. >4 total → 3 images + a "+N" box at right.
  const hasMore = event.count > 4;
  const previewImgs = hasMore ? event.photos.slice(0, 3) : event.photos.slice(0, 4);
  const moreCount = hasMore ? event.count - 3 : 0;
  React.useEffect(() => { if (!expanded) setManage(false); }, [expanded]);
  return (
    <div style={{ marginBottom: 10, background: P.graphite, borderLeft: `2px solid ${expanded ? P.gold : 'transparent'}` }}>
      <button onClick={onToggle} style={{
        width: '100%', background: 'transparent', border: 'none', cursor: 'pointer',
        padding: '14px 16px 12px', color: P.paper, textAlign: 'left',
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12,
      }}>
        <div style={{ minWidth: 0 }}>
          <Eyebrow color={expanded ? P.gold : P.mute}>{event.type.toUpperCase()}</Eyebrow>
          <div style={{
            fontFamily: T.display, fontSize: 17, fontWeight: 600, color: P.paper,
            marginTop: 5, letterSpacing: '-0.005em',
          }}>{event.count} {event.count === 1 ? 'PHOTO' : 'PHOTOS'}</div>
          <div style={{
            fontFamily: T.mono, fontSize: 8.5, color: P.mute, marginTop: 5,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            display: 'flex', gap: 7, flexWrap: 'wrap',
          }}>
            <span>{event.date}</span>
            <span>·</span>
            <span>{event.photographer}</span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 7, flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <VRConditionDot condition={event.condition} />
            <span style={{
              fontFamily: T.mono, fontSize: 8, letterSpacing: '0.12em',
              textTransform: 'uppercase', color: vrConditionColor(event.condition),
            }}>{event.condition}</span>
          </div>
          {event.damageCount > 0 && (
            <span style={{
              fontFamily: T.mono, fontSize: 8, fontWeight: 700, letterSpacing: '0.1em',
              color: P.paper, background: P.signal, padding: '2px 6px', textTransform: 'uppercase',
            }}>{event.damageCount} FLAGGED</span>
          )}
        </div>
      </button>

      {/* Collapsed preview strip */}
      {!expanded && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 3, padding: '0 16px 14px' }}>
          {previewImgs.map((p) => (
            <VRPhotoTile key={p.id} photo={p} onOpen={(ph) => onOpenPhoto(ph, event.photos)} showArea={false} />
          ))}
          {hasMore && (
            <button onClick={onToggle} style={{
              aspectRatio: '1 / 1', width: '100%', border: 'none', cursor: 'pointer',
              background: P.slate, color: P.paper,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
            }}>
              <span style={{ fontFamily: T.display, fontSize: 17, fontWeight: 700, lineHeight: 1 }}>+{moreCount}</span>
              <span style={{ fontFamily: T.mono, fontSize: 6.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: P.paper, opacity: 0.7 }}>MORE</span>
            </button>
          )}
        </div>
      )}

      {/* Expanded full grid */}
      {expanded && (
        <div style={{ padding: '0 16px 16px' }}>
          <div style={{
            fontFamily: T.body, fontSize: 11.5, color: P.mute, lineHeight: 1.5,
            marginBottom: 12, maxWidth: 300,
          }}>{event.note}</div>
          <div style={{
            display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12,
          }}>
            {event.areas.map(a => (
              <span key={a} style={{
                fontFamily: T.mono, fontSize: 8, letterSpacing: '0.12em', textTransform: 'uppercase',
                color: P.mute, border: `1px solid ${P.slate}`, padding: '4px 7px',
              }}>{a}</span>
            ))}
          </div>

          {/* Add / Manage controls */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
            <button onClick={() => onAddToEvent && onAddToEvent(event)} style={{
              flex: 1, padding: '10px 0', cursor: 'pointer',
              background: P.gold, border: 'none', color: P.ink,
              fontFamily: T.mono, fontSize: 9, fontWeight: 700, letterSpacing: '0.16em',
              textTransform: 'uppercase', display: 'inline-flex', alignItems: 'center',
              justifyContent: 'center', gap: 7,
            }}>
              <Icon name="add" size={14} color={P.ink} strokeWidth={2.2} /> ADD PHOTOS
            </button>
            <button onClick={() => setManage(m => !m)} style={{
              flex: 1, padding: '10px 0', cursor: 'pointer',
              background: manage ? P.signal : 'transparent',
              border: `1px solid ${manage ? P.signal : P.slate}`,
              color: manage ? P.paper : P.paper,
              fontFamily: T.mono, fontSize: 9, fontWeight: 600, letterSpacing: '0.16em',
              textTransform: 'uppercase',
            }}>{manage ? 'DONE' : 'MANAGE'}</button>
          </div>
          {manage && (
            <div style={{
              fontFamily: T.mono, fontSize: 8, color: P.mute, letterSpacing: '0.12em',
              textTransform: 'uppercase', marginBottom: 10,
            }}>Tap × to remove a photo from this event</div>
          )}

          {event.photos.length === 0 ? (
            <div style={{
              padding: '28px 16px', textAlign: 'center', border: `1px dashed ${P.slate}`,
              fontFamily: T.mono, fontSize: 9, color: P.mute, letterSpacing: '0.16em', textTransform: 'uppercase',
            }}>No photos in this event</div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4 }}>
              {event.photos.map(p => (
                <VRPhotoTile key={p.id} photo={p} onOpen={(ph) => onOpenPhoto(ph, event.photos)}
                  manage={manage} onDelete={(ph) => onDeletePhoto && onDeletePhoto(ph)} />
              ))}
            </div>
          )}
          {!manage && event.count > event.photos.length && (
            <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',
            }}>VIEW ALL {event.count} PHOTOS</button>
          )}
        </div>
      )}
    </div>
  );
}

// ── Capture sheet ──────────────────────────────────────────────────
// Lets a user beside the car pick the inspection event + area, then
// capture from camera or pick from library. Wires a real file input so
// it works on a phone.
function VRCaptureSheet({ vehicle, defaultEvent, targetEvent, onClose, onCapture }) {
  const [eventType, setEventType] = React.useState(targetEvent ? targetEvent.type : (defaultEvent || 'Evaluation'));
  const [area, setArea] = React.useState(targetEvent && targetEvent.areas[0] ? targetEvent.areas[0] : 'Exterior');
  const fileRef = React.useRef(null);
  const mode = React.useRef('library');

  const trigger = (m) => {
    mode.current = m;
    const inp = fileRef.current;
    if (!inp) return;
    inp.value = '';
    if (m === 'camera') inp.setAttribute('capture', 'environment');
    else inp.removeAttribute('capture');
    inp.click();
  };
  const onFiles = (e) => {
    const files = Array.from(e.target.files || []);
    if (files.length) onCapture(files, eventType, area, targetEvent ? targetEvent.id : null);
  };

  const Chip = ({ label, on, onClick }) => (
    <button onClick={onClick} style={{
      fontFamily: T.mono, fontSize: 9, fontWeight: 600, letterSpacing: '0.12em',
      textTransform: 'uppercase', cursor: 'pointer', padding: '8px 11px',
      background: on ? P.gold : 'transparent', color: on ? P.ink : P.paper,
      border: `1px solid ${on ? P.gold : P.slate}`, whiteSpace: 'nowrap',
    }}>{label}</button>
  );

  const Action = ({ icon, label, sub, onClick, primary }) => (
    <button onClick={onClick} style={{
      flex: 1, cursor: 'pointer', padding: '16px 12px',
      background: primary ? P.gold : P.ink, border: primary ? 'none' : `1px solid ${P.slate}`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
    }}>
      <Icon name={icon} size={24} color={primary ? P.ink : P.gold} strokeWidth={1.6} />
      <div style={{
        fontFamily: T.mono, fontSize: 10, fontWeight: 700, letterSpacing: '0.14em',
        textTransform: 'uppercase', color: primary ? P.ink : P.paper,
      }}>{label}</div>
      <div style={{
        fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.1em', textTransform: 'uppercase',
        color: primary ? 'rgba(10,10,11,0.6)' : P.mute,
      }}>{sub}</div>
    </button>
  );

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 90,
      display: 'flex', alignItems: 'flex-end',
      animation: 'sheetIn .25s cubic-bezier(.2,.7,.3,1)',
    }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(10,10,11,0.8)',
        backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
      }} />
      <div className="proto-scroll" style={{
        position: 'relative', width: '100%', maxHeight: '90%', overflow: 'auto',
        background: P.graphite, color: P.paper,
        borderTop: `1px solid ${P.gold}`, padding: '14px 22px 40px',
      }}>
        <div style={{ width: 40, height: 4, background: P.slate, margin: '0 auto 16px' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div>
            <Eyebrow color={P.gold}>{targetEvent ? 'ADD TO EVENT' : 'DOCUMENT VEHICLE'}</Eyebrow>
            <div style={{
              fontFamily: T.display, fontSize: 24, fontWeight: 700, color: P.paper,
              marginTop: 6, letterSpacing: '-0.015em',
            }}>{targetEvent ? targetEvent.type.toUpperCase() : 'ADD PHOTOS'}</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>

        {/* Event selector — hidden when adding to a fixed event */}
        {!targetEvent && (
          <div style={{ marginBottom: 16 }}>
            <Eyebrow color={P.mute} style={{ marginBottom: 8 }}>INSPECTION EVENT</Eyebrow>
            <div className="proto-scroll" style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 2 }}>
              {VR_EVENT_TYPES.map(t => (
                <Chip key={t} label={t} on={eventType === t} onClick={() => setEventType(t)} />
              ))}
            </div>
          </div>
        )}

        {/* Area selector */}
        <div style={{ marginBottom: 20 }}>
          <Eyebrow color={P.mute} style={{ marginBottom: 8 }}>VEHICLE AREA</Eyebrow>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {VR_AREAS.map(a => (
              <Chip key={a.name} label={a.name} on={area === a.name} onClick={() => setArea(a.name)} />
            ))}
          </div>
        </div>

        {/* Capture actions */}
        <div style={{ display: 'flex', gap: 8 }}>
          <Action icon="camera" label="Camera" sub="One or many" primary onClick={() => trigger('camera')} />
          <Action icon="gallery" label="Library" sub="Multi-select" onClick={() => trigger('library')} />
        </div>
        <div style={{
          fontFamily: T.mono, fontSize: 8, color: P.mute, letterSpacing: '0.12em',
          textTransform: 'uppercase', textAlign: 'center', marginTop: 14, lineHeight: 1.7,
        }}>
          UPLOADS TO {eventType.toUpperCase()} · {area.toUpperCase()}<br/>
          ODO {fmtMiles(vehicle.mileage || 0)} · PHOTOGRAPHER YOU
        </div>

        <input ref={fileRef} type="file" accept="image/*" multiple onChange={onFiles}
          style={{ display: 'none' }} />
      </div>
    </div>
  );
}

// ── Photo detail sheet ─────────────────────────────────────────────
function VRPhotoDetail({ photo, vehicle, onClose, onDelete }) {
  const Meta = ({ label, value, accent }) => (
    <div style={{ padding: '11px 0', borderBottom: `1px solid ${P.graphite}`, display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'baseline' }}>
      <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>
  );
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 95, animation: 'sheetIn .22s cubic-bezier(.2,.7,.3,1)' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(10,10,11,0.9)' }} />
      <div className="proto-scroll" style={{
        position: 'absolute', inset: 0, overflow: 'auto', background: P.ink, color: P.paper,
      }}>
        {/* Photo */}
        <div style={{ position: 'relative', width: '100%', aspectRatio: '4 / 3',
          background: photo.src ? P.ink : `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: 'cover' }} />}
          {!photo.src && (
            <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>
          )}
          <button onClick={onClose} style={{
            position: 'absolute', top: 16, right: 16, zIndex: 2,
            width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: 'rgba(10,10,11,0.7)', color: P.paper, fontFamily: T.mono, fontSize: 15,
            backdropFilter: 'blur(4px)',
          }}>×</button>
        </div>

        <div style={{ padding: '20px 22px 40px' }}>
          <Eyebrow color={P.gold}>{photo.area.toUpperCase()}</Eyebrow>
          <div style={{
            fontFamily: T.display, fontSize: 24, fontWeight: 700, color: P.paper,
            marginTop: 6, letterSpacing: '-0.015em',
          }}>{(photo.tags && photo.tags[1] ? photo.tags[1] : 'Photo').toUpperCase()}</div>

          {/* condition + damage banner */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '14px 0 4px' }}>
            <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: 10, padding: '10px 12px', background: 'rgba(122,36,24,0.18)',
              borderLeft: `2px solid ${P.signal}`,
              fontFamily: T.body, fontSize: 12, color: P.paper,
            }}>
              <span style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.16em', color: P.signal, textTransform: 'uppercase' }}>DAMAGE INDICATOR</span>
              <div style={{ marginTop: 4 }}>{photo.damage}</div>
            </div>
          )}

          <div style={{ marginTop: 18 }}>
            <Meta label="Date / Time" value={photo.time} />
            <Meta label="Event" value={photo.tags && photo.tags[1] ? photo.tags[1] : '—'} />
            <Meta label="Photographer" value={photo.photographer} />
            <Meta label="Odometer" value={fmtMiles(photo.odometer || 0)} />
            <Meta label="Condition" value={photo.condition} accent={vrConditionColor(photo.condition)} />
            <Meta label="Restoration Stage" value={photo.restoration || 'N/A'} />
            <Meta label="Associated Docs" value={photo.docs ? `${photo.docs} linked` : 'None'} accent={photo.docs ? P.gold : undefined} />
            <Meta label="Tags" value={(photo.tags || []).join(' · ')} />
          </div>

          {photo.note && (
            <div style={{ marginTop: 16 }}>
              <Eyebrow color={P.mute} style={{ marginBottom: 6 }}>NOTES</Eyebrow>
              <div style={{ fontFamily: T.body, fontSize: 13, color: P.paper, lineHeight: 1.55 }}>{photo.note}</div>
            </div>
          )}

          <div style={{ display: 'flex', gap: 8, marginTop: 22 }}>
            <button style={{
              flex: 1, padding: '12px 0', background: 'transparent', border: `1px solid ${P.slate}`,
              color: P.paper, fontFamily: T.mono, fontSize: 9, fontWeight: 600, letterSpacing: '0.18em',
              textTransform: 'uppercase', cursor: 'pointer',
            }}>EDIT METADATA</button>
            <button style={{
              flex: 1, padding: '12px 0', background: 'transparent', border: `1px solid ${P.slate}`,
              color: P.paper, fontFamily: T.mono, fontSize: 9, fontWeight: 600, letterSpacing: '0.18em',
              textTransform: 'uppercase', cursor: 'pointer',
            }}>LINK DOCUMENT</button>
          </div>
          <button onClick={() => onDelete && onDelete(photo)} style={{
            width: '100%', marginTop: 8, padding: '12px 0', background: 'transparent',
            border: `1px solid ${P.signal}`, color: P.signal,
            fontFamily: T.mono, fontSize: 9, fontWeight: 700, letterSpacing: '0.18em',
            textTransform: 'uppercase', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <Icon name="flag" size={13} color={P.signal} strokeWidth={1.8} /> DELETE PHOTO
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { VRConditionDot, VRPhotoTile, VREventCard, VRCaptureSheet, VRPhotoDetail });
