// ===========================================================
// GuestShelf — what a signed-out visitor has logged on this device.
//
// "I own this" on /list works without an account (data/store.js:
// addGuestCollectionItem), and those records migrate into the account on first
// login. Without this strip that add is invisible: the visitor ticks three
// albums, opens /collection, and is shown the same sales pitch as before with
// no sign their records exist. This is the receipt — and the reason to sign up,
// stated as what they'd lose rather than as a feature list.
//
// Renders nothing when there is nothing saved, so the marketing page is
// unchanged for a first-time visitor.
// ===========================================================
const { useState: useGsState, useEffect: useGsEffect } = React;

function GuestShelf({ albums, onSignup }) {
  const store = window.BBR_store;
  const [, force] = useGsState(0);

  // The store is the source of truth and mutates outside React (a tick on
  // /list, a migration on login), so re-render on its notifications.
  useGsEffect(() => (store ? store.subscribe(() => force((n) => n + 1)) : undefined), []);

  if (!store || !store.isGuest()) return null;
  const rows = store.collectionV2 || [];
  if (!rows.length) return null;

  const byslug = {};
  (albums || []).forEach((a) => { byslug[a.slug] = a; });

  // Only count what we actually have a figure for. A guest add without a chosen
  // pressing has est_value null, and inventing a number here would be exactly
  // the fabricated-value problem the rest of the site has been clearing out.
  const priced = rows.filter((r) => r.est_value != null);
  const total = priced.reduce((s, r) => s + Number(r.est_value || 0), 0);
  const max = store.guestMax ? store.guestMax() : 25;
  const full = store.guestFull && store.guestFull();

  const money = (n) => "£" + Math.round(n).toLocaleString("en-GB");

  return (
    <section className="gs" aria-labelledby="gs-h">
      <div className="gs-inner">
        <div className="gs-copy">
          <div className="gs-kicker">Saved on this device</div>
          <h2 className="gs-h" id="gs-h">
            {rows.length === 1 ? "One record logged" : rows.length + " records logged"}
            {priced.length ? <span className="gs-val"> · {money(total)}</span> : null}
          </h2>
          <p className="gs-lede">
            {full
              ? "That's as far as the trial goes. Create a free account and these " +
                rows.length + " records come with you — then add as many as you like."
              : "These live in this browser only. Create a free account and they move across with you, " +
                "start tracking market value, and count towards your rank."}
          </p>
          <div className="gs-cta">
            <button className="mc-btn solid" onClick={onSignup}>
              Keep {rows.length === 1 ? "my record" : "my " + rows.length + " records"}
            </button>
            {!full ? <span className="gs-fine">{rows.length} of {max} in the trial</span> : null}
          </div>
          {/* Say what the figure covers. Showing "3 records · £260" when one of
              the three is priced reads as the total for all three. */}
          {!priced.length ? (
            <div className="gs-fine gs-fine-block">
              No valuation yet — pick a pressing when you add a record and we'll price it.
            </div>
          ) : priced.length < rows.length ? (
            <div className="gs-fine gs-fine-block">
              {priced.length} of {rows.length} priced — choose a pressing for the
              {rows.length - priced.length === 1 ? " other one" : " other " + (rows.length - priced.length)} to value them.
            </div>
          ) : null}
        </div>

        <ul className="gs-covers">
          {rows.slice(0, 6).map((r) => {
            const a = r.slug ? byslug[r.slug] : null;
            const label = (r.title || (a && a.title) || "Record") +
                          (r.artist || (a && a.artist) ? " — " + (r.artist || a.artist) : "");
            return (
              <li key={r.id} className="gs-cover" title={label}>
                {a
                  ? <img src={"/covers/" + a.slug + ".jpg"} alt={label} width="72" height="72" loading="lazy" />
                  : <span className="gs-cover-txt" aria-label={label}>{(r.title || "?").slice(0, 2)}</span>}
              </li>
            );
          })}
          {rows.length > 6 ? <li className="gs-cover gs-more">+{rows.length - 6}</li> : null}
        </ul>
      </div>
    </section>
  );
}

Object.assign(window, { GuestShelf });
