/* Lodestay — Messages. List-detail inside one destination: the conversations on
   the left, one conversation on the right. A thread is not a route — it is the
   selected state of this screen, which is why it has no breadcrumb of its own.

   The chain worth watching: opening an unread conversation marks the host's
   messages read, and the count in the top bar moves with it. Nothing is stored
   on the thread except `read` — the badge counts the predicate. */
(() => {
  const {
    Button, Textarea, Badge, Separator, Avatar,
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription,
  } = window.OriginDesignSystem_7c998b;

  function ThreadRow({ thread, data, active, onOpen }) {
    const host = hostById(data.hosts, thread.hostId);
    const listing = listingById(data.listings, thread.listingId);
    const last = THREAD_FLAGS.lastMessage(thread);
    const unread = THREAD_FLAGS.unreadCount(thread);
    return (
      <button type="button" className="ls-threadrow" aria-current={active} onClick={() => onOpen(thread)}>
        <Avatar size={32} src={host.avatar} alt="" fallback={host.name.split(" ").map((w) => w[0]).join("")} />
        <span className="ls-threadrow__name">
          <span>{host.name.split(" ")[0]}{unread ? <span className="ls-threadrow__dot" style={{ display: "inline-block", marginInlineStart: 6 }} aria-label={unread + " unread"} /> : null}</span>
          <span className="ls-note" title={formatAbsolute(last.at)}>{formatWhen(last.at, data.now)}</span>
        </span>
        <span className="ls-threadrow__snip">{listing.name} — {last.from === "host" ? "" : "You: "}{last.body}</span>
      </button>
    );
  }

  function InboxScreen({ data, selectedId, onSelect, onSend, onNavigate }) {
    const threads = threadsByRecency(data.threads);
    const unread = unreadThreads(data.threads);
    const thread = threadById(threads, selectedId) || threads[0];
    const host = thread ? hostById(data.hosts, thread.hostId) : null;
    const listing = thread ? listingById(data.listings, thread.listingId) : null;
    const booking = thread && thread.bookingId ? bookingById(data.bookings, thread.bookingId) : null;
    const [draft, setDraft] = React.useState("");
    React.useEffect(() => { setDraft(""); }, [selectedId]);

    return (
      <div className="ls-page">
        <PageHead
          path="/inbox" onNavigate={onNavigate}
          title="Messages"
          lede={threads.length + " conversations · " + (unread.length ? unread.length + (unread.length === 1 ? " with something unread" : " with something unread") : "nothing unread")}
        />

        <div className="ls-inbox">
          <div className="ls-threadlist">
            {threads.map((t) => (
              <ThreadRow key={t.id} thread={t} data={data} active={thread && t.id === thread.id} onOpen={(x) => onSelect(x.id)} />
            ))}
          </div>

          {!thread ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="message-circle" size={18} /></EmptyMedia>
                <EmptyTitle>No conversations</EmptyTitle>
                <EmptyDescription>Messages to hosts start from a place or a trip.</EmptyDescription>
              </EmptyHeader>
            </Empty>
          ) : (
            <Card>
              <CardHeader>
                <CardTitle><button type="button" className="ls-link" onClick={() => onNavigate("/hosts/" + host.id)}>{host.name}</button></CardTitle>
                <CardDescription>
                  {listing.name} · {booking
                    ? statusValue(BOOKING_STATUS, booking.status).label.toLowerCase() + " · " + formatStayLine(booking.checkIn, booking.checkOut, booking.guests)
                    : "an enquiry, nothing booked"}
                </CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="ls-msgs">
                  {thread.messages.map((message) => (
                    <div className={"ls-msg" + (message.from === "guest" ? " ls-msg--guest" : "")} key={message.id}>
                      <p className="ls-msg__body">{message.body}</p>
                      <span className="ls-msg__time" title={formatAbsolute(message.at)}>
                        {message.from === "guest" ? "You" : host.name.split(" ")[0]} · {formatWhen(message.at, data.now)}
                      </span>
                    </div>
                  ))}
                </div>
              </CardPanel>
              <CardFooter className="ls-stack ls-stack--tight" style={{ alignItems: "stretch" }}>
                <Textarea
                  rows={3} value={draft} aria-label={"Message " + host.name.split(" ")[0]}
                  placeholder={booking && BOOKING_FLAGS.wantsArrivalPlan(booking, data.now) ? "Arriving around six, if that works." : "Write to " + host.name.split(" ")[0] + "…"}
                  onChange={(e) => setDraft(e.target.value)}
                />
                <div className="ls-row" style={{ justifyContent: "space-between" }}>
                  <span className="ls-note">{replyLine(host)}{booking ? " · " : ""}{booking ? <button type="button" className="ls-link" onClick={() => onNavigate("/trips/" + booking.id)}>Open the trip</button> : null}</span>
                  <Button size="sm" disabled={!draft.trim()} onClick={() => { onSend(thread, draft.trim()); setDraft(""); }}>Send</Button>
                </div>
              </CardFooter>
            </Card>
          )}
        </div>
      </div>
    );
  }

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