/* Lodestay — one trip. The record screen: what was agreed, what has been paid,
   what is still owed, and what the guest can do about it — derived from the
   booking's status and its payments, never a fixed set of buttons.

   COMMIT MODEL: instant. Every action here applies immediately; the
   consequential ones raise an undo toast, the irreversible one (cancelling)
   opens a confirm dialog quoting the refund from refundFor, and the two that
   need typing (arrival time, review) open staged dialogs. Nothing on this
   screen is a form field. */
(() => {
  const {
    Button, Badge, Separator, Alert, AlertTitle, AlertDescription,
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableFooter, TableRow, TableHead, TableCell,
  } = window.OriginDesignSystem_7c998b;

  function TripScreen({ booking, data, onNavigate, onRun }) {
    const listing = listingById(data.listings, booking.listingId);
    const host = hostById(data.hosts, booking.hostId);
    const quote = quoteForBooking(booking);
    const payments = paymentsOf(booking);
    const paid = paidCents(booking);
    const refunded = refundedCents(booking);
    const owed = owedCents(booking);
    const failed = failedPayments(booking);
    const reason = BOOKING_FLAGS.reasonNeedsYou(booking, data.now);
    const refund = refundFor(booking, data.now);
    const thread = threadForBooking(data.threads, booking.id);
    const last = thread ? THREAD_FLAGS.lastMessage(thread) : null;
    const policy = policyOf(booking.cancelPolicy);
    const nights = nightsBetween(booking.checkIn, booking.checkOut);

    return (
      <div className="ls-page">
        <PageHead
          path="/trips/:id" params={{ id: booking.id }} labels={{ "/trips/:id": listing.name }} onNavigate={onNavigate}
          title={listing.name}
          lede={formatStayLine(booking.checkIn, booking.checkOut, booking.guests) + " · " + labelOf(NEIGHBOURHOODS, listing.neighbourhood) + " · booking " + booking.reference}
          actions={<Transitions transitions={bookingTransitions(booking, data.now)} onRun={(t) => onRun(booking, t)} />}
        >
          <span className="ls-row ls-row--tight" style={{ marginTop: "var(--space-2)" }}>
            <StatusBadge values={BOOKING_STATUS} value={booking.status} size="default" />
            {BOOKING_FLAGS.isStaying(booking, data.now) ? <span className="ls-note">You are here now — checkout {formatDayFull(booking.checkOut)}</span> : null}
            {BOOKING_FLAGS.isUpcoming(booking, data.now) ? <span className="ls-note">{formatCountdown(booking.checkIn, data.now)}</span> : null}
          </span>
        </PageHead>

        {reason ? (
          <Alert variant={failed.length ? "error" : "warning"}>
            <Icon name={failed.length ? "credit-card" : "clock" } size={16} />
            <AlertTitle>{reason}</AlertTitle>
            <AlertDescription>
              {failed.length
                ? failed[0].failedReason + " " + formatPrice(failed[0].amountCents) + " is still owed, and " + host.name.split(" ")[0] + " has not been told."
                : BOOKING_FLAGS.isBalanceDueSoon(booking, data.now)
                  ? formatPrice(BOOKING_FLAGS.scheduledBalance(booking).amountCents) + " comes off the " + methodById(data.methods, BOOKING_FLAGS.scheduledBalance(booking).method).brand + " on " + formatDayFull(BOOKING_FLAGS.scheduledBalance(booking).dueAt) + ". Pay it now if you would rather not wait for it."
                  : BOOKING_FLAGS.wantsArrivalPlan(booking, data.now)
                    ? host.name.split(" ")[0] + " asked what time you get there — check-in is " + formatDayFull(booking.checkIn) + " and they are out between 16:00 and 18:00."
                    : "The review window closes " + formatDayFull(booking.checkOut + STAY_POLICY.reviewWindowDays * 864e5) + "."}
            </AlertDescription>
          </Alert>
        ) : null}

        {booking.closedNote ? (
          <Alert variant="info">
            <Icon name="message-square-quote" size={16} />
            <AlertTitle>{host.name.split(" ")[0]} said no, {formatWhen(booking.closedAt, data.now)}</AlertTitle>
            <AlertDescription>“{booking.closedNote}” Nothing was ever charged.</AlertDescription>
          </Alert>
        ) : null}

        <div className="ls-columns">
          <div className="ls-col">
            <Card>
              <CardHeader>
                <CardTitle>The stay</CardTitle>
                <CardDescription>Booked {formatAbsolute(booking.bookedAt)} · {labelOf(BOOKING_MODES, listing.bookingMode)}</CardDescription>
              </CardHeader>
              <CardPanel>
                <Facts items={[
                  { label: "Check in", value: formatDayFull(booking.checkIn) + ", from " + checkInClock(booking.checkIn) },
                  { label: "Check out", value: formatDayFull(booking.checkOut) + ", by " + checkInClock(booking.checkOut) },
                  { label: "Guests", value: formatGuests(booking.guests) },
                  { label: "What for", value: labelOf(TRIP_PURPOSES, booking.purpose) },
                  { label: "Nights", value: formatNights(nights) },
                  { label: "Cancellation", value: policy.label },
                ]} />
              </CardPanel>
              <CardFooter className="ls-stack ls-stack--tight" style={{ alignItems: "flex-start" }}>
                <span className="ls-note">
                  {booking.arrivalPlan
                    ? "Arrival, as told to " + host.name.split(" ")[0] + ": “" + booking.arrivalPlan + "”"
                    : BOOKING_FLAGS.isOpen(booking)
                      ? "No arrival time shared yet."
                      : "No arrival time was shared."}
                </span>
                {booking.cancelReason ? <span className="ls-note">Cancelled {formatWhen(booking.closedAt, data.now)} — {labelOf(CANCEL_REASONS, booking.cancelReason).toLowerCase()}.</span> : null}
              </CardFooter>
            </Card>

            {payments.length ? (
              <Card>
                <CardHeader>
                  <CardTitle>Money</CardTitle>
                  <CardDescription>{payments.length} {payments.length === 1 ? "movement" : "movements"} on this booking</CardDescription>
                </CardHeader>
                <CardPanel style={{ padding: 0 }}>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Movement</TableHead>
                        <TableHead>Card</TableHead>
                        <TableHead>When</TableHead>
                        <TableHead style={{ textAlign: "right" }}>Amount</TableHead>
                        <TableHead>Status</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {payments.map((payment) => {
                        const method = methodById(data.methods, payment.method);
                        return (
                          <TableRow key={payment.id}>
                            <TableCell>{labelOf(PAYMENT_KINDS, payment.kind)}</TableCell>
                            <TableCell className="ls-muted">{method.brand} ···· {method.last4}</TableCell>
                            <TableCell title={formatAbsolute(payment.paidAt || payment.dueAt)}>
                              {payment.paidAt ? formatDayFull(payment.paidAt) : "Due " + formatDayFull(payment.dueAt)}
                            </TableCell>
                            <TableCell style={{ textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{payment.kind === "refund" ? "−" : ""}{formatPrice(payment.amountCents)}</TableCell>
                            <TableCell><StatusBadge values={PAYMENT_STATUS} value={payment.status} /></TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                    <TableFooter>
                      <TableRow>
                        <TableCell colSpan={3}>{refunded ? "Paid, less what came back" : owed ? "Paid so far" : "Paid"}</TableCell>
                        <TableCell style={{ textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{formatPrice(paid - refunded)}</TableCell>
                        <TableCell className="ls-muted">{owed ? formatPrice(owed) + " to come" : "of " + formatPrice(quote.total)}</TableCell>
                      </TableRow>
                    </TableFooter>
                  </Table>
                </CardPanel>
                <CardFooter>
                  <Button variant="outline" size="sm" onClick={() => onNavigate("/trips/" + booking.id + "/receipt")}>Receipt<Icon name="arrow-right" size={16} /></Button>
                </CardFooter>
              </Card>
            ) : (
              <Alert>
                <Icon name="wallet" size={16} />
                <AlertTitle>Nothing has been charged</AlertTitle>
                <AlertDescription>{booking.status === "requested" ? "The card is only charged if " + host.name.split(" ")[0] + " accepts — " + formatPrice(quote.total) + " for " + formatNights(nights) + "." : "This request was never accepted, so no money moved."}</AlertDescription>
              </Alert>
            )}

            {booking.review ? (
              <Card>
                <CardHeader>
                  <CardTitle>Your review</CardTitle>
                  <CardDescription>Written {formatWhen(booking.review.at, data.now)} · {booking.review.rating} out of 5</CardDescription>
                </CardHeader>
                <CardPanel><p className="ls-review__body">{booking.review.body}</p></CardPanel>
              </Card>
            ) : null}
          </div>

          <div className="ls-col">
            <div className="ls-stack">
              <Card>
                <CardHeader>
                  <CardTitle>What it cost</CardTitle>
                  <CardDescription>The rate agreed on {formatDay(booking.bookedAt)}, not today's</CardDescription>
                </CardHeader>
                <CardPanel>
                  <QuoteBreakdown
                    quote={quote}
                    extra={refunded
                      ? [{ label: "Refunded " + formatWhen(booking.closedAt, data.now), amount: "−" + formatPrice(refunded), muted: true }, { label: "Kept", amount: formatPrice(paid - refunded) }]
                      : owed
                        ? [{ label: "Paid", amount: formatPrice(paid) }, { label: "Still to come", amount: formatPrice(owed) }]
                        : null}
                  />
                </CardPanel>
                {BOOKING_FLAGS.canCancel(booking, data.now) ? (
                  <CardFooter>
                    <span className="ls-note">
                      {refund.isFree
                        ? "Cancel before " + formatDayFull(refund.freeUntil) + " and all " + formatPrice(refund.refundCents) + " comes back."
                        : "Cancelling now returns " + formatPrice(refund.refundCents) + " of the " + formatPrice(paid) + " paid — the free window closed " + formatDay(refund.freeUntil) + "."}
                    </span>
                  </CardFooter>
                ) : null}
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>{host.name.split(" ")[0]}</CardTitle>
                  <CardDescription>{replyLine(host)}</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} onClick={() => onNavigate("/hosts/" + host.id)} />
                    {last ? (
                      <span className="ls-note">
                        {last.from === "host" ? host.name.split(" ")[0] : "You"}, {formatWhen(last.at, data.now)}: “{last.body.length > 96 ? last.body.slice(0, 96) + "…" : last.body}”
                      </span>
                    ) : null}
                  </div>
                </CardPanel>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>Getting there</CardTitle>
                  <CardDescription>{labelOf(NEIGHBOURHOODS, listing.neighbourhood)} · {listing.stairs === 0 ? "no stairs" : listing.stairs + " steps to the door"}</CardDescription>
                </CardHeader>
                <CardPanel style={{ padding: 0 }}>
                  <div style={{ position: "relative", height: "13rem", 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>
                  <Button variant="outline" size="sm" onClick={() => onNavigate("/stays/" + listing.id)}>See the place</Button>
                </CardFooter>
              </Card>
            </div>
          </div>
        </div>
      </div>
    );
  }

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