/* Live shipment view — a customer's ShipCargo-linked shipment.

   Everything on this screen comes from Viamar's operations system (synced
   every 15 minutes): journey steps and dates, vessel, container, the
   customer's own vehicles (VIN last 6 only) and receiving photos (shown only
   once the cargo is received). No placeholder payments, documents or stock
   photos — if ShipCargo doesn't know it, the screen doesn't claim it.

   window.ViamarOperations = { LiveShipmentView, OperationsSummary, PhotoLightbox } */

const LSV_ITEM_STATUS = {
  pending_intake: { t: 'Waiting for drop-off', c: T.muted },
  received: { t: 'At our yard', c: T.navy3 },
  loaded: { t: 'Loaded in container', c: T.amber },
  released: { t: 'Released', c: T.green },
  delivered: { t: 'Delivered', c: T.green },
};

function lsvModel() {
  return window.ViamarOperationsModel || null;
}

function lsvDay(iso) {
  const m = lsvModel();
  return (m && m.formatDay && m.formatDay(iso)) || null;
}

function lsvAgo(iso) {
  const t = Date.parse(iso || '');
  if (!Number.isFinite(t)) return null;
  const min = Math.round((Date.now() - t) / 60000);
  if (min < 2) return 'just now';
  if (min < 60) return min + ' min ago';
  const h = Math.round(min / 60);
  return h < 36 ? h + ' h ago' : Math.round(h / 24) + ' days ago';
}

/* ── Journey tracker ─────────────────────────────────────────────── */

function LsvJourney({ journey, compact }) {
  const currentIndex = journey.reduce((acc, s, i) => (s.done ? i : acc), -1);
  if (compact) {
    return (
      <div>
        {journey.map((step, i) => {
          const isCurrent = i === currentIndex;
          const last = i === journey.length - 1;
          return (
            <div key={step.key} style={{ display: 'flex', gap: 12 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <LsvDot done={step.done} current={isCurrent} />
                {!last && <div style={{ width: 2, flex: 1, minHeight: 18, background: journey[i + 1].done ? 'rgba(255,255,255,0.55)' : 'rgba(255,255,255,0.16)' }} />}
              </div>
              <div style={{ paddingBottom: last ? 0 : 14, flex: 1, display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                <span style={{ fontFamily: FB, fontSize: 13, fontWeight: isCurrent ? 800 : 600, color: step.done ? '#fff' : 'rgba(255,255,255,0.5)' }}>{step.label}</span>
                <span style={{ fontFamily: FM, fontSize: 10.5, color: step.done ? 'rgba(255,255,255,0.75)' : 'rgba(255,255,255,0.45)', whiteSpace: 'nowrap' }}>{step.date ? lsvDay(step.date) : ''}</span>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${journey.length}, minmax(0, 1fr))` }}>
      {journey.map((step, i) => {
        const isCurrent = i === currentIndex;
        return (
          <div key={step.key} style={{ minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flex: 1, height: 2, background: i === 0 ? 'transparent' : step.done ? 'rgba(255,255,255,0.55)' : 'rgba(255,255,255,0.16)' }} />
              <LsvDot done={step.done} current={isCurrent} />
              <div style={{ flex: 1, height: 2, background: i === journey.length - 1 ? 'transparent' : journey[i + 1].done ? 'rgba(255,255,255,0.55)' : 'rgba(255,255,255,0.16)' }} />
            </div>
            <div style={{ textAlign: 'center', padding: '9px 4px 0' }}>
              <div style={{ fontFamily: FB, fontSize: 12, lineHeight: 1.3, fontWeight: isCurrent ? 800 : 600, color: step.done ? '#fff' : 'rgba(255,255,255,0.5)' }}>{step.label}</div>
              <div style={{ fontFamily: FM, fontSize: 10, marginTop: 3, color: step.done ? 'rgba(255,255,255,0.7)' : 'rgba(255,255,255,0.42)' }}>
                {step.date ? (step.done ? '' : 'Expected ') + lsvDay(step.date) : ' '}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function LsvDot({ done, current }) {
  const size = current ? 22 : 18;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: current ? T.red : done ? '#fff' : 'transparent',
      border: done || current ? 'none' : '2px solid rgba(255,255,255,0.3)',
      boxShadow: current ? '0 0 0 5px rgba(221,28,36,0.28)' : 'none',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {done && !current && <Icon name="check" size={11} color={T.navy} stroke={3.2} />}
      {current && <div style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff' }} />}
    </div>
  );
}

/* ── Status hero ─────────────────────────────────────────────────── */

function LsvHero({ ops, guidance, compact }) {
  const m = lsvModel();
  const next = guidance && guidance.next;
  const days = next && next.date && m ? m.dayDiff(next.date) : null;
  const updated = lsvAgo(ops.source_updated_at);
  return (
    <div style={{ background: T.navy, borderRadius: compact ? 18 : 20, padding: compact ? '18px 16px' : '24px 26px 22px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', right: -40, top: -60, width: 220, height: 220, borderRadius: '50%', background: 'radial-gradient(circle, rgba(221,28,36,0.22), transparent 70%)' }} />
      <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: FM, fontSize: 9.5, letterSpacing: 1.2, textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)' }}>Right now</div>
          <div style={{ fontFamily: FD, fontWeight: 800, fontSize: compact ? 22 : 28, letterSpacing: '-0.02em', lineHeight: 1.1, marginTop: 6 }}>{guidance ? guidance.status : 'Shipment in progress'}</div>
          {guidance && <div style={{ fontFamily: FB, fontSize: compact ? 12.5 : 14, color: 'rgba(255,255,255,0.78)', marginTop: 8, lineHeight: 1.45 }}>{guidance.nextUpdate}</div>}
        </div>
        {days != null && days > 0 && (
          <div style={{ flexShrink: 0, textAlign: 'center', background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 14, padding: compact ? '8px 12px' : '10px 16px' }}>
            <div style={{ fontFamily: FD, fontWeight: 800, fontSize: compact ? 24 : 30, lineHeight: 1 }}>{days}</div>
            <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: 0.6, textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginTop: 4 }}>day{days === 1 ? '' : 's'} to {next.key === 'arrived' ? 'arrival' : next.key === 'sailed' ? 'sailing' : 'next step'}</div>
          </div>
        )}
      </div>

      {ops.journey.length > 0 && (
        <div style={{ position: 'relative', marginTop: compact ? 18 : 24 }}>
          <LsvJourney journey={ops.journey} compact={compact} />
        </div>
      )}

      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: compact ? 16 : 20, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.1)' }}>
        <Icon name="checkC" size={15} color={T.green} stroke={2} />
        <span style={{ fontFamily: FB, fontSize: 12.5, color: 'rgba(255,255,255,0.85)', flex: 1, minWidth: 180 }}>{guidance ? guidance.nextAction : 'Your Viamar team is handling this shipment.'}</span>
        {updated && <span style={{ fontFamily: FM, fontSize: 9.5, color: 'rgba(255,255,255,0.45)', letterSpacing: 0.3 }}>Updated {updated}</span>}
      </div>
    </div>
  );
}

/* ── Voyage + cargo ──────────────────────────────────────────────── */

function LsvFact({ icon, label, value, mono }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 0', borderTop: '1px solid ' + T.line2 }}>
      <div style={{ width: 32, height: 32, borderRadius: 9, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={icon} size={16} color={T.navy3} stroke={1.9} />
      </div>
      <div style={{ fontFamily: FM, fontSize: 9, letterSpacing: 0.8, textTransform: 'uppercase', color: T.faint, width: 78, flexShrink: 0 }}>{label}</div>
      <div style={{ fontFamily: mono ? FM : FB, fontWeight: 700, fontSize: mono ? 12.5 : 13.5, color: value ? T.ink : T.faint, minWidth: 0, overflowWrap: 'anywhere' }}>{value || 'Not confirmed yet'}</div>
    </div>
  );
}

function LsvVoyage({ ops }) {
  const b = ops.bookings[0] || null;
  const box = b && b.containers[0];
  return (
    <Card pad={18}>
      <div style={{ fontFamily: FB, fontWeight: 800, fontSize: 15, color: T.ink, marginBottom: 6 }}>Voyage</div>
      {b ? (
        <div>
          <LsvFact icon="ship" label="Vessel" value={b.vessel} />
          <LsvFact icon="anchor" label="Carrier" value={b.carrier_name} />
          <LsvFact icon="clock" label="Sails" value={lsvDay(b.sailing_date)} />
          <LsvFact icon="pin" label="Arrives" value={lsvDay(b.eta)} />
          <LsvFact icon="box" label="Container" value={box ? box.container_number + (box.seal_number ? ' · seal ' + box.seal_number : '') : null} mono />
          <LsvFact icon="doc" label="Booking" value={b.carrier_booking_ref} mono />
        </div>
      ) : (
        <div style={{ fontFamily: FB, fontSize: 13, color: T.muted, lineHeight: 1.5, paddingTop: 6 }}>
          We have not booked a vessel for this shipment yet. Sailing details appear here as soon as the carrier confirms.
        </div>
      )}
    </Card>
  );
}

function LsvCargo({ ops }) {
  return (
    <Card pad={18}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
        <span style={{ fontFamily: FB, fontWeight: 800, fontSize: 15, color: T.ink }}>Your cargo</span>
        <span style={{ fontFamily: FM, fontSize: 10, color: T.muted }}>{ops.items.length} item{ops.items.length === 1 ? '' : 's'}</span>
      </div>
      {ops.items.map((item, i) => {
        const st = LSV_ITEM_STATUS[item.processing_status] || null;
        return (
          <div key={item.item_id || i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderTop: '1px solid ' + T.line2 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: T.paper, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name={item.cargo_type === 'vehicle' ? 'car' : 'box'} size={21} color={T.navy} stroke={1.9} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 14, color: T.ink }}>{item.description || (item.cargo_type === 'vehicle' ? 'Vehicle' : 'Cargo')}</div>
              <div style={{ fontFamily: FM, fontSize: 10.5, color: T.muted, marginTop: 2 }}>
                {[item.vin_last6 ? 'VIN ending ' + item.vin_last6 : null, item.condition ? item.condition.charAt(0).toUpperCase() + item.condition.slice(1) : null].filter(Boolean).join(' · ') || ' '}
              </div>
            </div>
            {st && <span style={{ fontFamily: FM, fontSize: 9.5, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', color: st.c, background: st.c + '17', borderRadius: 999, padding: '4px 9px', whiteSpace: 'nowrap' }}>{st.t}</span>}
          </div>
        );
      })}
    </Card>
  );
}

/* ── Photos ──────────────────────────────────────────────────────── */

/* Receiving photos are private: each is fetched with the session bearer
   (Authorization header) into a temporary blob: URL held only by this
   screen — revoked on unmount and dropped when the session changes (sign-out,
   another customer, rotated bearer). See app/photo-access-model.js. */
function useShipmentPhotos() {
  const [version, setVersion] = React.useState(0);
  const [link, setLink] = React.useState(null);
  React.useEffect(() => {
    const access = window.ViamarPhotoAccess;
    const connected = access && access.connectPhotoCache
      ? access.connectPhotoCache({ win: window, api: window.ViamarAPI, onChange: () => setVersion((v) => v + 1) })
      : null;
    setLink(connected);
    return () => { if (connected) connected.disconnect(); };
  }, []);
  const cache = link ? link.cache : null;
  return {
    ready: !!cache,
    // Bumps on every load and on every session reset, so callers re-request
    // what they show under the new session (the cache skips known photos).
    version,
    request: (photo) => { if (cache && photo && photo.photo_id) cache.request(photo.photo_id); },
    src: (photo) => {
      if (!photo) return null;
      if (photo.photo_id) return cache ? cache.urlFor(photo.photo_id) : null;
      return photo.url || null;
    },
  };
}

function PhotoLightbox({ photos, index, onClose, onIndex, srcOf, request }) {
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') onIndex((index + 1) % photos.length);
      if (e.key === 'ArrowLeft') onIndex((index - 1 + photos.length) % photos.length);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [index, photos.length, onClose, onIndex]);
  const photo = photos[index];
  React.useEffect(() => { if (request && photo) request(photo); }, [photo, request]);
  if (!photo) return null;
  const src = srcOf ? srcOf(photo) : photo.url;
  const navBtn = (side, label, to) => (
    <button type="button" aria-label={label} onClick={(e) => { e.stopPropagation(); onIndex(to); }}
      style={{ position: 'absolute', top: '50%', [side]: 16, marginTop: -24, width: 48, height: 48, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,0.12)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <Icon name={side === 'left' ? 'chevL' : 'chevR'} size={24} color="#fff" stroke={2.4} />
    </button>
  );
  // Portal to <body>: the app shells scale-to-fit with a transform, which
  // would otherwise trap a fixed overlay inside the frame.
  const overlay = (
    <div role="dialog" aria-modal="true" aria-label="Receiving photos" onClick={onClose}
      style={{ position: 'fixed', inset: 0, zIndex: 2147483000, background: 'rgba(6,16,28,0.94)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {src ? (
        <img src={src} alt={'Receiving photo ' + (index + 1) + ' of ' + photos.length} onClick={(e) => e.stopPropagation()}
          style={{ maxWidth: 'min(92vw, 1100px)', maxHeight: '82vh', borderRadius: 12, objectFit: 'contain', boxShadow: '0 20px 60px rgba(0,0,0,0.45)' }} />
      ) : (
        <div style={{ fontFamily: FB, fontSize: 13, color: 'rgba(255,255,255,0.7)' }}>Loading photo…</div>
      )}
      {photos.length > 1 && navBtn('left', 'Previous photo', (index - 1 + photos.length) % photos.length)}
      {photos.length > 1 && navBtn('right', 'Next photo', (index + 1) % photos.length)}
      <button type="button" aria-label="Close photos" onClick={onClose}
        style={{ position: 'absolute', top: 16, right: 16, width: 44, height: 44, borderRadius: '50%', border: 'none', background: 'rgba(255,255,255,0.12)', color: '#fff', fontSize: 26, lineHeight: 1, cursor: 'pointer' }}>×</button>
      <div style={{ position: 'absolute', bottom: 22, left: 0, right: 0, textAlign: 'center', fontFamily: FM, fontSize: 11, color: 'rgba(255,255,255,0.7)', letterSpacing: 0.5 }}>
        {index + 1} / {photos.length}
      </div>
    </div>
  );
  return window.ReactDOM && ReactDOM.createPortal && document.body ? ReactDOM.createPortal(overlay, document.body) : overlay;
}

function LsvPhotos({ ops, compact }) {
  const [open, setOpen] = React.useState(null);
  const photos = ops.items.reduce((all, item) => all.concat(item.images), []);
  const received = ops.journey.find((s) => s.key === 'received');
  const receivedOn = received && received.done && received.date ? lsvDay(received.date) : null;
  const visible = compact ? 6 : 12;
  const access = useShipmentPhotos();
  const shownIds = photos.slice(0, visible).map((p) => p.photo_id || '').join(',');
  React.useEffect(() => {
    photos.slice(0, visible).forEach(access.request);
  }, [access.ready, access.version, shownIds]);
  return (
    <div>
      <SectionHead title="Receiving photos" action={photos.length ? photos.length + ' photos' + (receivedOn ? ' · ' + receivedOn : '') : null} />
      {photos.length === 0 ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, border: '1.5px dashed ' + T.line, borderRadius: 14, padding: '16px 18px', background: '#fff' }}>
          <Icon name="camera" size={20} color={T.faint} stroke={1.9} />
          <div style={{ fontFamily: FB, fontSize: 13, color: T.muted, lineHeight: 1.45 }}>
            {received && received.done
              ? 'Photos from our yard will appear here shortly.'
              : 'We photograph every vehicle and shipment when it arrives at our yard. Your photos appear here once we receive your cargo.'}
          </div>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: compact ? 'repeat(auto-fill, minmax(96px, 1fr))' : 'repeat(auto-fill, minmax(118px, 1fr))', gap: 8 }}>
          {photos.slice(0, visible).map((p, i) => {
            const more = i === visible - 1 && photos.length > visible;
            const src = access.src(p);
            return (
              <button key={p.photo_id || p.url} type="button" onClick={() => setOpen(i)} aria-label={more ? 'View all ' + photos.length + ' photos' : 'Open photo ' + (i + 1)}
                style={{ position: 'relative', padding: 0, border: 'none', borderRadius: 11, overflow: 'hidden', aspectRatio: '1 / 1', cursor: 'zoom-in', background: T.line2 }}>
                {src
                  ? <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                  : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="camera" size={18} color={T.faint} stroke={1.9} /></div>}
                {more && (
                  <div style={{ position: 'absolute', inset: 0, background: 'rgba(10,27,46,0.62)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FB, fontWeight: 800, fontSize: 16, color: '#fff' }}>
                    +{photos.length - visible + 1}
                  </div>
                )}
              </button>
            );
          })}
        </div>
      )}
      {photos.length > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, fontFamily: FB, fontSize: 12, color: T.muted }}>
          <Icon name="shield" size={14} color={T.green} stroke={2} />
          Taken by our team when your cargo arrived at our yard.
        </div>
      )}
      {open != null && <PhotoLightbox photos={photos} index={open} onIndex={setOpen} onClose={() => setOpen(null)} srcOf={access.src} request={access.request} />}
    </div>
  );
}

/* ── Help ────────────────────────────────────────────────────────── */

function LsvHelp({ onMessage, compact }) {
  const message = () => {
    if (onMessage) onMessage({ reason: 'status', source: 'live-shipment' });
    else if (window.ViamarChat && window.ViamarChat.open) window.ViamarChat.open({ reason: 'status', source: 'live-shipment' });
    else window.location.href = 'tel:+18002777570';
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap', background: '#fff', border: '1px solid ' + T.line2, borderRadius: 16, padding: compact ? '14px 15px' : '16px 18px' }}>
      <div style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(221,28,36,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name="user" size={20} color={T.red} stroke={2} />
      </div>
      <div style={{ flex: 1, minWidth: 180 }}>
        <div style={{ fontFamily: FB, fontWeight: 800, fontSize: 14, color: T.ink }}>Questions about this shipment?</div>
        <div style={{ fontFamily: FB, fontSize: 12, color: T.muted, marginTop: 2 }}>Message your Viamar team or call 1-800-277-7570</div>
      </div>
      <Btn variant="navy" size="sm" icon="phone" onClick={message} style={compact ? { width: '100%' } : undefined}>Message Viamar</Btn>
    </div>
  );
}

/* ── Page ────────────────────────────────────────────────────────── */

function LiveShipmentView({ s, onMessage, compact, header = true }) {
  const m = lsvModel();
  const ops = m && m.normalize ? m.normalize(s && s.operations) : null;
  if (!ops) return null;
  const guidance = (s && s.operationsGuidance) || (m.guidance ? m.guidance(ops) : null);
  const route = [s.from, s.to].filter((v) => v && v !== 'Destination pending').join(' → ');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: compact ? 14 : 20, paddingBottom: compact ? 24 : 56 }}>
      {window.ViamarNextStep && <ViamarNextStep.RequestPreferences ship={s} />}
      {header && (
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: FM, fontSize: 10.5, color: T.muted, letterSpacing: 0.6, textTransform: 'uppercase' }}>House bill · {ops.hbl_ref || 'pending'}</div>
            <Display size={compact ? 22 : 28} color={T.ink}>{s.cargo}</Display>
            {route && <div style={{ fontFamily: FB, fontSize: 14, color: T.body, marginTop: 5 }}>{route}</div>}
          </div>
          <Status kind={s.kind} />
        </div>
      )}

      <LsvHero ops={ops} guidance={guidance} compact={compact} />

      <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : 'repeat(auto-fit, minmax(300px, 1fr))', gap: compact ? 14 : 18, alignItems: 'start' }}>
        <LsvVoyage ops={ops} />
        <LsvCargo ops={ops} />
      </div>

      <LsvPhotos ops={ops} compact={compact} />

      <LsvHelp onMessage={onMessage} compact={compact} />
    </div>
  );
}

/* Back-compat: older surfaces render just the operations body. */
function OperationsSummary({ operations }) {
  return <LiveShipmentView s={{ operations, kind: 'transit' }} header={false} />;
}

window.ViamarOperations = { LiveShipmentView, OperationsSummary, PhotoLightbox };
