// ============================================================================
// StreetView — building Street View thumbnail per ticket / building.
//
// Two modes, picked at runtime:
//   (1) REAL — if window.OPS_GMAPS_KEY is set (Static Street View API key),
//       hits Google's API and shows the real photo.
//   (2) PLACEHOLDER — clean navy thumbnail with map-pin glyph. Click opens
//       Google Maps Street View for the address in a new tab.
//
// To enable real thumbnails, add ONE line to app/index.html before the rest:
//   <script>window.OPS_GMAPS_KEY = 'YOUR_STATIC_STREETVIEW_API_KEY';</script>
//
// Pricing: Static Street View is $7/1000 requests (no free tier as of 2024).
// ============================================================================

function streetViewMapUrl(address) {
  // Opens Google Maps interactive Street View for the address.
  const q = encodeURIComponent(address || '');
  return `https://www.google.com/maps?q=${q}&layer=c&cbll=&cbp=11,0,0,0,0`;
}

function googleMapsUrl(address) {
  // Opens Google Maps centred on the address with a pin dropped.
  return `https://www.google.com/maps?q=${encodeURIComponent(address || '')}`;
}

function StreetView({ address, size = 'card', label = 'Street View' }) {
  const key = window.OPS_GMAPS_KEY;
  const dims = size === 'lg'    ? [560, 280]
             : size === 'card'  ? [320, 180]
             : size === 'pill'  ? [160, 88]
             : /* thumb */        [220, 124];
  const [w, h] = dims;
  const liveSrc = key
    ? `https://maps.googleapis.com/maps/api/streetview?size=${w}x${h}&location=${encodeURIComponent(address)}&fov=80&pitch=0&key=${key}`
    : null;
  const [ok, setOk] = React.useState(!!liveSrc);
  React.useEffect(() => { setOk(!!liveSrc); }, [address, liveSrc]);

  return (
    <a className={`streetview sv-${size}`}
       href={streetViewMapUrl(address)} target="_blank" rel="noopener noreferrer"
       title={`Open Street View of ${address} in Google Maps`}
       onClick={e => e.stopPropagation()}>
      {liveSrc && ok ? (
        <img src={liveSrc} alt={`Street View of ${address}`} loading="lazy"
             onError={() => setOk(false)} />
      ) : (
        <div className="sv-placeholder" aria-hidden="true">
          <span className="sv-pin"><Icon name="eye" /></span>
          <span className="sv-label">{label}</span>
        </div>
      )}
      <span className="sv-chip" aria-hidden="true"><Icon name="external-link" /></span>
    </a>
  );
}

// MapPin — static Google Map of the address with the pin dropped. Clicking
// opens Maps directions / pin in a new tab. Same key as StreetView.
function MapPin({ address, size = 'card', label = 'Where it is' }) {
  const key = window.OPS_GMAPS_KEY;
  const dims = size === 'lg'    ? [560, 280]
             : size === 'card'  ? [320, 180]
             : size === 'pill'  ? [160, 88]
             : /* thumb */        [220, 124];
  const [w, h] = dims;
  // muted styled map: hide POI labels, keep roads + buildings so the pin reads.
  const style = '&style=feature:poi|visibility:off&style=feature:transit|visibility:off';
  const liveSrc = key
    ? `https://maps.googleapis.com/maps/api/staticmap?size=${w}x${h}&zoom=17&maptype=roadmap&markers=color:0xE2574A%7Csize:mid%7C${encodeURIComponent(address)}${style}&key=${key}`
    : null;
  const [ok, setOk] = React.useState(!!liveSrc);
  React.useEffect(() => { setOk(!!liveSrc); }, [address, liveSrc]);

  return (
    <a className={`streetview map-pin sv-${size}`}
       href={googleMapsUrl(address)} target="_blank" rel="noopener noreferrer"
       title={`Open ${address} in Google Maps`}
       onClick={e => e.stopPropagation()}>
      {liveSrc && ok ? (
        <img src={liveSrc} alt={`Map of ${address}`} loading="lazy"
             onError={() => setOk(false)} />
      ) : (
        <div className="sv-placeholder mp-placeholder" aria-hidden="true">
          <svg className="mp-grid" viewBox="0 0 100 60" preserveAspectRatio="none">
            {/* faint road grid so the placeholder reads as "a map" */}
            <line x1="0" y1="20" x2="100" y2="20" />
            <line x1="0" y1="40" x2="100" y2="40" />
            <line x1="25" y1="0" x2="25" y2="60" />
            <line x1="55" y1="0" x2="55" y2="60" />
            <line x1="80" y1="0" x2="80" y2="60" />
          </svg>
          <span className="mp-pin"><Icon name="map-pin" /></span>
          <span className="sv-label">{label}</span>
        </div>
      )}
      <span className="sv-chip" aria-hidden="true"><Icon name="external-link" /></span>
    </a>
  );
}

// BuildingLocation — pair StreetView + MapPin side by side. The default
// shape used in ticket detail / building drawer.
function BuildingLocation({ address, size = 'card' }) {
  return (
    <div className={`bldg-loc bldg-loc-${size}`}>
      <StreetView address={address} size={size} />
      <MapPin address={address} size={size} />
    </div>
  );
}

Object.assign(window, { StreetView, MapPin, BuildingLocation, streetViewMapUrl, googleMapsUrl });
