// Loves & nopes page — read-only view of the prefs blob.
// Population and edits happen exclusively via the Telegram bot's /prefs flow.
const { useMemo: useMemoLoves } = React;

const PEOPLE = [
  { key: "karen",    label: "karen ♀" },
  { key: "mingyuan", label: "ming yuan ♂" },
];
const POLARITIES = [
  { key: "love", label: "💗 loves" },
  { key: "nope", label: "🚫 nopes" },
];

function LovesEntry({ entry }) {
  return (
    <li className="loves-entry">
      <span className="loves-entry-text">{entry.text}</span>
      {entry.note ? <span className="loves-entry-note"> · {entry.note}</span> : null}
    </li>
  );
}

function LovesSection({ entries, label }) {
  return (
    <div className="loves-section">
      <div className="loves-section-label">{label}</div>
      {entries.length === 0 ? (
        <div className="loves-section-empty">(none yet)</div>
      ) : (
        <ul className="loves-list">
          {entries.map((e) => <LovesEntry key={e.id} entry={e} />)}
        </ul>
      )}
    </div>
  );
}

function PersonCard({ person, label, entries }) {
  // Newest at the bottom for each list — feels natural for an album that
  // grows over time. createdAt may be missing on hand-edited entries; fall
  // back to insertion order in that case.
  const sorted = [...entries].sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0));
  return (
    <div className="loves-card">
      <h2 className="loves-card-name">{label}</h2>
      {POLARITIES.map((p) => (
        <LovesSection
          key={p.key}
          label={p.label}
          entries={sorted.filter((e) => e.polarity === p.key)}
        />
      ))}
    </div>
  );
}

function LovesPage({ prefs }) {
  const entries = useMemoLoves(() => prefs?.entries || [], [prefs]);

  if (entries.length === 0) {
    return (
      <section className="loves-page" data-screen-label="04 Loves">
        <h1 className="hero-title">loves &amp; nopes.</h1>
        <p className="hero-sub">the small things that make us, us.</p>
        <div className="loves-empty">
          no loves or nopes yet — try <code>/prefs</code> in the bot ♥
        </div>
      </section>
    );
  }

  return (
    <section className="loves-page" data-screen-label="04 Loves">
      <h1 className="hero-title">loves &amp; nopes.</h1>
      <p className="hero-sub">the small things that make us, us.</p>
      <div className="loves-grid">
        {PEOPLE.map((p) => (
          <PersonCard
            key={p.key}
            person={p.key}
            label={p.label}
            entries={entries.filter((e) => e.person === p.key)}
          />
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { LovesPage });
