'use client';

import { MapPin, Plane } from 'lucide-react';
import { useState } from 'react';
import type { LayoverAirportSummary } from '@/services/flights/layoverAirport.client';
import { placePhotoUrl } from '@/services/flights/layoverDisplay';

export interface LayoverHeroProps {
  summary: LayoverAirportSummary;
  iataCode: string;
  /** Falls back to the itinerary's own name while the request is in flight. */
  fallbackName: string;
}

/**
 * Airport name, place and picture.
 *
 * The image is decoration, not information — every fact it sits behind is also
 * written out in text — so it is `alt=""` and the block degrades to a tinted
 * panel when there is no photo, rather than to a broken frame. Google supplies
 * photos for most airports and none for some; both have to look deliberate.
 */
export default function LayoverHero({ summary, iataCode, fallbackName }: LayoverHeroProps) {
  const [failed, setFailed] = useState(false);
  const src = failed ? null : placePhotoUrl(summary.photos[0]);

  const name = summary.airport.name || fallbackName;
  // formattedAddress carries the country in words ("Desert Highway, Amman,
  // Jordan"); city alone is the fallback when Google has no address on file.
  const place = summary.airport.formattedAddress || summary.airport.city;
  const credit = summary.photos[0]?.attributions?.[0];

  return (
    <div className={`layover-hero${src ? '' : ' layover-hero--bare'}`}>
      {src ? (
        /* Plain <img>, not next/image: the proxy answers with a 302 to a signed
           lh3 URL that Google rotates hourly, so an optimiser caching the
           resolved target would be serving a dead link within the hour. */
        // eslint-disable-next-line @next/next/no-img-element
        <img className="layover-hero__img" src={src} alt="" loading="eager" onError={() => setFailed(true)} />
      ) : (
        <span className="layover-hero__placeholder" aria-hidden="true">
          <Plane size={44} strokeWidth={1.25} />
        </span>
      )}

      <div className="layover-hero__scrim" aria-hidden="true" />

      <div className="layover-hero__text">
        <h3 className="layover-hero__name">
          {name} <span className="layover-hero__iata">({iataCode})</span>
        </h3>
        <p className="layover-hero__place">
          <MapPin size={14} aria-hidden="true" />
          <span>{place}</span>
        </p>
      </div>

      {/* Photo attribution is a Places display condition wherever a photo is shown. */}
      {src && credit?.name && (
        <p className="layover-hero__credit">
          Photo:{' '}
          {credit.uri ? (
            <a href={credit.uri} target="_blank" rel="noreferrer noopener">
              {credit.name}
            </a>
          ) : (
            credit.name
          )}
        </p>
      )}
    </div>
  );
}
