/* Lodestay — one place. The record screen: what it is, where it is, who owns
   it, what it costs for the dates in the scope, and what the guest can do with
   it — which is derived from its availability, never a fixed pair of buttons.

   One data state, four branches of the same conditional: open (the booking
   card), on hold (the same card, its button disabled with the reason and the
   time it frees up), booked and paused (no booking card at all — there is
   nothing to disable, so the screen says what to do instead).

   No calendar is drawn. This design system's Calendar selects a single day and
   a stay is a range; stating the dates in words is honest, and the README
   reports the gap. */
(() => {
  const {
    Button, Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Alert, AlertTitle, AlertDescription, Separator, Badge,
  } = window.OriginDesignSystem_7c998b;

  function StayScreen({ listing, data, scope, saved, onSave, onNavigate, onRun, onFindSimilar }) {
    const host = hostById(data.hosts, listing.hostId);
    const quote = quoteForListing(listing, scope);
    const nights = quote.nights;
    const rating = ratingOf(listing);
    const five = fiveStarShare(listing);
    const policy = policyOf(listing.cancelPolicy);
    const transitions = listingTransitions(listing, Object.assign({ nights: nights }, scope), data.now);
    const bookable = LISTING_FLAGS.isBookable(listing) || LISTING_FLAGS.isHeld(listing);
    const stayedWith = bookingsWithHost(data.bookings, host.id).filter((b) => b.status === "completed");

    return (
      <div className="ls-page">
        <PageHead
          path="/stays/:id" params={{ id: listing.id }} labels={{ "/stays/:id": listing.name }} onNavigate={onNavigate}
          title={listing.name}
          lede={labelOf(PLACE_KINDS, listing.kind) + " in " + labelOf(NEIGHBOURHOODS, listing.neighbourhood) + " · sleeps " + listing.sleeps + " in " + listing.bedrooms + (listing.bedrooms === 1 ? " bedroom" : " bedrooms")}
          actions={<><Rating listing={listing} /><SaveButton listing={listing} saved={saved} onToggle={onSave} size="sm" /></>}
        />

        <div className="ls-gallery">
          <Photo label={listing.photos[0]} icon={iconOfKind(listing)} shape="wide" />
          <div className="ls-gallery__side">
            <Photo label={listing.photos[1]} icon="image" shape="flat" />
            <Photo label={listing.photos[2]} icon="image" shape="flat" />
          </div>
        </div>

        <div className="ls-columns">
          <div className="ls-col">
            <div className="ls-section">
              <p className="ls-lede" style={{ maxWidth: "62ch", fontSize: "var(--text-base)", color: "var(--foreground)" }}>{listing.blurb}</p>
              <Facts items={[
                { label: "Sleeps", value: listing.sleeps + " in " + listing.beds + (listing.beds === 1 ? " bed" : " beds") },
                { label: "Bathrooms", value: listing.baths },
                { label: "Stairs to the door", value: listing.stairs === 0 ? "None" : listing.stairs + " steps" },
                { label: "Minimum stay", value: formatNights(listing.minNights) },
                { label: "Booking", value: labelOf(BOOKING_MODES, listing.bookingMode) },
                { label: "Listed", value: formatWhen(listing.listedAt, data.now) },
              ]} />
            </div>

            <div className="ls-section">
              <SectionHead title="What is here" />
              <AmenityList values={listing.amenities} />
            </div>

            <Card>
              <CardHeader>
                <CardTitle>Your host</CardTitle>
                <CardDescription>{policy.label} cancellation · {labelOf(BOOKING_MODES, listing.bookingMode).toLowerCase()}</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="ls-stack ls-stack--tight">
                  <Who person={host} meta={"Hosting since " + new Date(host.joinedAt).getFullYear() + " · lives in " + host.lives} size={44} onClick={() => onNavigate("/hosts/" + host.id)} />
                  <span className="ls-note">{replyLine(host)} · speaks {host.languages.join(", ")}</span>
                  {stayedWith.length ? (
                    <span className="ls-note">You have stayed with {host.name.split(" ")[0]} {stayedWith.length === 1 ? "once" : stayedWith.length + " times"} — {stayedWith.map((b) => labelOf(NEIGHBOURHOODS, listingById(data.listings, b.listingId).neighbourhood) + ", " + formatDay(b.checkIn)).join(" and ")}.</span>
                  ) : null}
                </div>
              </CardPanel>
              <CardFooter>
                <Button variant="outline" size="sm" onClick={() => onNavigate("/inbox")}><Icon name="message-circle" size={15} />Message host</Button>
              </CardFooter>
            </Card>

            <div className="ls-section">
              <SectionHead
                title={listing.reviews.length ? "What guests said" : "No reviews yet"}
                note={rating === null
                  ? listing.reviews.length
                    ? listing.reviews.length + " reviews so far — a rating needs " + STAY_POLICY.ratingMinReviews
                    : "Listed " + formatWhen(listing.listedAt, data.now) + ", nobody has stayed yet"
                  : formatRating(rating) + " from " + listing.reviews.length + " reviews · " + Math.round(five * listing.reviews.length) + " of them at five stars"}
              />
              {listing.reviews.length ? (
                <div className="ls-stack">
                  {listing.reviews.map((review) => (
                    <div className="ls-review" key={review.id}>
                      <div className="ls-row">
                        <span className="ls-person__name">{review.name}</span>
                        <span className="ls-rating"><Icon name="star" size={12} />{review.rating}</span>
                        <span className="ls-note" title={formatAbsolute(review.at)}>{formatWhen(review.at, data.now)}</span>
                      </div>
                      <p className="ls-review__body">{review.body}</p>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="ls-note" style={{ maxWidth: "52ch" }}>{host.name.split(" ")[0]} has {data.listings.filter((l) => l.hostId === host.id).length} places on Lodestay; this one opened {formatWhen(listing.listedAt, data.now)}.</p>
              )}
            </div>
          </div>

          <div className="ls-col">
            <div className="ls-sticky ls-stack">
              {bookable ? (
                <Card>
                  <CardHeader>
                    <CardTitle><span className="ls-price ls-price--lg">{formatPrice(quote.total)}</span> <span className="ls-muted" style={{ fontWeight: 400, fontSize: "var(--text-sm)" }}>for {formatNights(nights)}</span></CardTitle>
                    <CardDescription>{formatStayLine(scope.checkIn, scope.checkOut, scope.guests)}</CardDescription>
                  </CardHeader>
                  <CardPanel>
                    <QuoteBreakdown quote={quote} />
                  </CardPanel>
                  <CardFooter className="ls-stack ls-stack--tight" style={{ alignItems: "stretch" }}>
                    <Transitions transitions={transitions} onRun={(t) => onRun(listing, t)} size="lg" />
                    <span className="ls-note">
                      {LISTING_FLAGS.isHeld(listing)
                        ? "Another guest is at the checkout screen with these dates. The hold expires at " + formatHoldClock(listing.holdUntil) + " — " + formatCountdown(listing.holdUntil, data.now) + "."
                        : LISTING_FLAGS.isInstant(listing)
                          ? "Nothing is charged until you confirm on the next screen. " + policy.note
                          : host.name.split(" ")[0] + " answers requests in about " + (host.replyMinutes < 60 ? host.replyMinutes + " minutes" : Math.round(host.replyMinutes / 60) + " hours") + ". Nothing is charged until they accept. " + policy.note}
                    </span>
                  </CardFooter>
                </Card>
              ) : (
                <Alert variant={listing.availability === "held" ? "warning" : "info"}>
                  <Icon name="calendar-x" size={16} />
                  <AlertTitle>{listing.availability === "booked" ? "Taken for " + formatStayRange(scope.checkIn, scope.checkOut) : host.name.split(" ")[0] + " has paused this place"}</AlertTitle>
                  <AlertDescription>
                    {listing.availability === "booked"
                      ? "Somebody else booked these dates. It is still in your saved list, so it will come back the moment the dates change."
                      : "Not taking bookings for any dates at the moment. Nothing is charged and nothing is held."}
                  </AlertDescription>
                </Alert>
              )}

              {!bookable ? (
                <Button variant="outline" onClick={() => onFindSimilar(listing)}>Find similar places in {labelOf(NEIGHBOURHOODS, listing.neighbourhood)}</Button>
              ) : null}

              <Card>
                <CardHeader>
                  <CardTitle>Where it is</CardTitle>
                  <CardDescription>{labelOf(NEIGHBOURHOODS, listing.neighbourhood)}, {LODESTAY_PRODUCT.city}</CardDescription>
                </CardHeader>
                <CardPanel style={{ padding: 0 }}>
                  <div style={{ position: "relative", height: "15rem", overflow: "hidden", borderRadius: "var(--radius-lg)" }}>
                    <MapPane
                      points={[{ id: listing.id, lat: listing.lat, lng: listing.lng, label: "", variant: "dot", title: listing.name }]}
                      center={[listing.lat, listing.lng]}
                      zoom={15}
                      interactive={false}
                      fit={false}
                    />
                  </div>
                </CardPanel>
                <CardFooter>
                  <span className="ls-note">The pin shows the street. The door number arrives with the booking confirmation.</span>
                </CardFooter>
              </Card>
            </div>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { StayScreen });
})();
