/* The Whole Table — screens. Babel JSX. Exports to window. */

const { useState: useStateS } = React;

/* ===================== HOME ===================== */
function Home({ t, onOpen, go }) {
  const posts = window.TWT_DATA.posts;
  const feature = posts.find((p) => p.feature) || posts[0];
  const recent = posts.filter((p) => p.id !== feature.id);
  const hero = t.homeHero || "full";

  return (
    <main className="home">
      {/* manifesto strip */}
      <section className="manifesto">
        <p>
          A travelling journal of taste — and a guide to who actually gets a seat.
          Every place is read across six dimensions, and <em>access is never a footnote</em>.
        </p>
      </section>

      {/* hero */}
      <section className={"hero hero-" + hero}>
        <div className="hero-media" onClick={() => onOpen(feature.id)}>
          <Slot id={feature.slot} ratio={hero === "split" ? "4 / 5" : "16 / 9"}
            placeholder="Drop your hero photo" src={feature.photo} />
        </div>
        <div className="hero-text">
          <span className="kicker">Latest entry — {feature.city}</span>
          <h1 className="hero-title" onClick={() => onOpen(feature.id)}>{feature.title}</h1>
          <p className="hero-dek">{feature.excerpt}</p>
          <div className="hero-meta">
            <span>{feature.restaurant}</span>
            <span className="dot-sep">{"\u00b7"}</span>
            <span>{feature.cuisine}</span>
            <span className="dot-sep">{"\u00b7"}</span>
            <span>{feature.readMins} min</span>
          </div>
          <button className="btn-read" onClick={() => onOpen(feature.id)}>Read the entry {"\u2192"}</button>
        </div>
      </section>

      {/* recent grid */}
      <section className="recent">
        <header className="section-head">
          <h2>Recent entries</h2>
          <button className="link-btn" onClick={() => go("browse")}>Browse all {"\u2192"}</button>
        </header>
        <div className="grid">
          {recent.map((p) => (
            <PostCard key={p.id} post={p} onOpen={onOpen} layout="col" />
          ))}
        </div>
      </section>

      {/* city globe */}
      <section className="globe-sec">
        <header className="section-head">
          <h2>Where the table has been</h2>
          <span className="kicker">Find a city, find a meal</span>
        </header>
        <CityGlobe posts={posts} onOpen={onOpen} />
      </section>

      {/* access promise */}
      <section className="promise" onClick={() => onOpen("essay-rating")}>
        <span className="kicker">The method</span>
        <p>
          “I review the door before the dish.” Read why every entry rates step-free
          entry, restrooms, transit and sensory load in plain language.
        </p>
        <span className="readmore">The manifesto {"\u2192"}</span>
      </section>
    </main>
  );
}

/* ===================== BROWSE ===================== */
function Browse({ t, onOpen, go }) {
  const posts = window.TWT_DATA.posts;
  const [filter, setFilter] = useStateS("all");
  const [sort, setSort] = useStateS("recent");

  const filters = [
    { k: "all", label: "All entries" },
    { k: "stepfree", label: "Step-free entry" },
    { k: "wc", label: "Accessible restroom" },
    { k: "budget", label: "Budget ($\u2013$$)" },
    { k: "splurge", label: "Splurge ($$$+)" },
    { k: "essay", label: "Essays" },
  ];

  function match(p) {
    switch (filter) {
      case "stepfree": return p.access && p.access.stepFree;
      case "wc": return p.access && p.access.accessibleRestroom;
      case "budget": return p.price != null && p.price <= 2;
      case "splurge": return p.price != null && p.price >= 3;
      case "essay": return p.isEssay;
      default: return true;
    }
  }
  let list = posts.filter(match);
  if (sort === "access") {
    list = [...list].sort((a, b) => (b.dimensions?.access || 0) - (a.dimensions?.access || 0));
  } else if (sort === "value") {
    list = [...list].sort((a, b) => (b.dimensions?.price || 0) - (a.dimensions?.price || 0));
  }

  return (
    <main className="browse">
      <header className="browse-head">
        <h1>The index</h1>
        <p className="browse-sub">{posts.length} entries across {new Set(posts.filter(p => !p.isEssay).map(p => p.city).filter(Boolean)).size} cities. Filter by access or price.</p>
      </header>

      <div className="filter-bar">
        <div className="filter-pills" role="tablist">
          {filters.map((f) => (
            <button key={f.k} role="tab" aria-selected={filter === f.k}
              className={"pill" + (filter === f.k ? " active" : "")}
              onClick={() => setFilter(f.k)}>{f.label}</button>
          ))}
        </div>
        <label className="sort">
          <span>Sort</span>
          <select value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="recent">Most recent</option>
            <option value="access">Best access</option>
            <option value="value">Best value</option>
          </select>
        </label>
      </div>

      <div className="browse-list">
        {list.length === 0 ? (
          <p className="empty">No entries match that filter yet.</p>
        ) : (
          list.map((p) => <PostCard key={p.id} post={p} onOpen={onOpen} layout="row" />)
        )}
      </div>
    </main>
  );
}

/* ===================== POST ===================== */
function Post({ t, id, onOpen, go }) {
  const posts = window.TWT_DATA.posts;
  const post = posts.find((p) => p.id === id) || posts[0];
  const idx = posts.findIndex((p) => p.id === post.id);
  const next = posts[(idx + 1) % posts.length];
  const profileStyle = t.profileStyle || "bars";
  const postLayout = t.postLayout || "aside";

  return (
    <main className={"post post-" + postLayout}>
      <button className="back" onClick={() => go("browse")}>{"\u2190"} The index</button>

      <header className="post-head">
        <span className="kicker">
          {post.isEssay ? "Essay" : post.cuisine}
          {post.city && !post.isEssay ? " \u00b7 " + post.city : ""}
        </span>
        <h1 className="post-title">{post.title}</h1>
        <p className="post-dek">{post.excerpt}</p>
        <div className="post-byline">
          <span>By Sophia Chan</span>
          <span className="dot-sep">{"\u00b7"}</span>
          <span>{post.date}</span>
          <span className="dot-sep">{"\u00b7"}</span>
          <span>{post.readMins} min read</span>
          {post.price != null ? (<><span className="dot-sep">{"\u00b7"}</span><PriceTag price={post.price} /></>) : null}
        </div>
      </header>

      {!post.isEssay ? (
        <figure className="post-hero">
          <Slot id={post.slot} ratio="16 / 9" placeholder={`${post.city} \u2014 hero photo`} radius={4} src={post.photo} />
        </figure>
      ) : null}

      <div className="post-body-wrap">
        <article className="post-body">
          {post.body.map((b, i) => {
            if (b.type === "p") return <p key={i}>{b.text}</p>;
            if (b.type === "h") return <h2 key={i}>{b.text}</h2>;
            if (b.type === "quote")
              return (
                <blockquote key={i}>
                  <p>{b.text}</p>
                  {b.cite ? <cite>{b.cite}</cite> : null}
                </blockquote>
              );
            return null;
          })}

          {/* in-body gallery */}
          {post.galleryCount > 0 ? (
            <div className={"gallery g-" + post.galleryCount}>
              {Array.from({ length: post.galleryCount }).map((_, i) => (
                <Slot key={i} id={post.slot + "-g" + i} ratio={i === 0 ? "3 / 2" : "1 / 1"}
                  placeholder={`Photo ${i + 1}`} src={post.gallery && post.gallery[i]} />
              ))}
            </div>
          ) : null}
        </article>

        {!post.isEssay ? (
          <aside className="post-aside">
            <div className="aside-sticky">
              <DiningProfile post={post} variant={profileStyle} />
              <AccessPanel post={post} />
            </div>
          </aside>
        ) : null}
      </div>

      {/* next */}
      <footer className="post-next" onClick={() => onOpen(next.id)}>
        <span className="kicker">Next entry</span>
        <h3>{next.title}</h3>
        <span className="readmore">{next.restaurant ? next.restaurant + " \u00b7 " : ""}{next.city} {"\u2192"}</span>
      </footer>
    </main>
  );
}

Object.assign(window, { Home, Browse, Post });
