/* ============================================================
   The Carnation — directory detail, events, saved & 404
   ============================================================ */

/* ===================== DIRECTORY — PLACE DETAIL ===================== */
function PlacePage({ slug }) {
  const D = C();
  useStore();
  const l = D.byDir(slug);
  useEffect(() => { window.scrollTo(0, 0); }, [slug]);
  if (!l) {
    return <main className="route"><section className="section"><div className="wrap wrap--narrow">
      <p className="note">That listing could not be found. <a href="#/local-index" style={{color:"var(--red)"}}>Back to the Local Index →</a></p>
    </div></section></main>;
  }
  const related = D.DIRECTORY_LISTINGS.filter((x) => x.cat === l.cat && x.slug !== slug).slice(0, 3);
  const featured = D.articlesFor(slug);
  const kind = D.kindOf(l);
  const isSpace = kind === "space";
  const services = l.services || l.offers;
  const events = D.eventsForVenue(l.name);
  const GAL_PLATES = ["window", "bench", "press", "ledger", "marquee", "campus"];
  const facts = [
    ["Location", l.address], ["Hours", l.hours],
    l.capacity ? ["Capacity", l.capacity] : null,
    ["Phone", l.phone], l.web ? ["Web", l.web] : null,
  ].filter(Boolean);
  const bookingHref = l.bookingUrl || (l.web ? (l.web.startsWith("http") ? l.web : "https://" + l.web) : null) || telHref(l.phone) || "#/submit";
  return (
    <main className="route art">
      <div className="wrap wrap--mid">
        <a className="backlink" href="#/local-index">← The Local Index</a>
        <header className="art__head">
          <div className="art__cat">{D.KIND_LABELS[kind]} · {l.cat}</div>
          <h1 className="art__title">{l.name}</h1>
          <p className="art__dek">{l.blurb}</p>
        </header>
      </div>
      <div className="wrap wrap--mid"><Cover variant={l.plate} tag={l.cat} slot={"cover:dir:" + l.slug} className="art__cover" alt={l.name} /></div>
      <div className="wrap wrap--mid">
        <div className="placegrid">
          <div className="placefacts">
            {facts.map((f) => {
              const [k, v] = f;
              let val = v;
              if (k === "Location") val = <a href={D.mapsSearchUrl ? D.mapsSearchUrl(v) : v} target="_blank" rel="noopener" className="placefact__link">{v}</a>;
              else if (k === "Phone") { const tel = telHref(v); val = tel ? <a href={tel} className="placefact__link">{v}</a> : v; }
              else if (k === "Web") { const href = v.startsWith("http") ? v : "https://" + v; val = <a href={href} target="_blank" rel="noopener" className="placefact__link">{v}</a>; }
              return (
                <div className="placefact" key={k}>
                  <span className="placefact__k">{k}</span>
                  <span className="placefact__v">{val}</span>
                </div>
              );
            })}
          </div>
          <div className="placeside">
            <PlaceLinks l={l} kind={kind} />
            {l.booking && (
              <div className="placebook">
                <a className="btn btn--red" href={bookingHref} target={bookingHref.startsWith("#") || bookingHref.startsWith("tel:") ? undefined : "_blank"} rel="noopener">{isSpace ? "Book or inquire" : "Get in touch"} <span className="arw">→</span></a>
                <p className="note placeside__note">{l.booking}</p>
              </div>
            )}
            {l.spot && <a className="btn btn--line" href={"#/spotlight/" + l.spot}>Read the Spotlight <span className="arw">→</span></a>}
            <a className="btn btn--line" href="#/submit">Suggest an edit</a>
            <p className="note placeside__note">Listings are maintained by The Carnation.</p>
            <p className="note placeside__note">Something out of date? <a href="#/submit" style={{color:"var(--red)"}}>Tell us →</a></p>
          </div>
        </div>
      </div>

      {l.amenities && (
        <section className="section section--tight placesec">
          <div className="wrap wrap--mid">
            <SecRule title={isSpace ? "Amenities & features" : "Good to know"} />
            <div className="amenities">{l.amenities.map((a) => <span className="amenity" key={a}>{a}</span>)}</div>
          </div>
        </section>
      )}

      {services && (
        <section className="section section--tight placesec">
          <div className="wrap wrap--mid">
            <SecRule title={kind === "resource" ? "What it offers" : "Services"} />
            <ul className="svc-list">{services.map((x) => <li className="svc" key={x}>{x}</li>)}</ul>
          </div>
        </section>
      )}

      {l.gallery && (
        <section className="section section--tight placesec">
          <div className="wrap wrap--mid">
            <SecRule title="The space" meta="Photos" />
            <div className="gallery">
              {Array.from({ length: l.gallery }).map((_, i) => (
                <Cover key={i} variant={GAL_PLATES[(i + 1) % GAL_PLATES.length]} slot={"gallery:dir:" + l.slug + ":" + (i + 1)} className="gallery__img" alt={l.name + " — photo " + (i + 1)} />
              ))}
            </div>
          </div>
        </section>
      )}

      <section className="section section--tight placesec">
        <div className="wrap wrap--mid">
          <SecRule title={events.length ? "Happenings here" : "Nearby & upcoming"} meta="The calendar" href="#/events" />
          <div className="ev-list">
            {(events.length ? events : [...D.EVENTS].sort((a, b) => (a.ts || 0) - (b.ts || 0)).slice(0, 3)).map((e) => (
              <a className="ev" href={"#/event/" + e.slug} key={e.slug}>
                <div className="ev__when">{e.dateLabel}</div>
                <div className="ev__body">
                  <span className="ev__cat">{e.cat} · {e.venue}</span>
                  <span className="ev__t">{e.title}</span>
                  <span className="ev__d">{e.blurb}</span>
                </div>
                <span className="ev__go arw">→</span>
              </a>
            ))}
          </div>
          {events.length === 0 && <p className="note placesec__cta">Hosting something at {l.name}? <a href="#/submit" style={{color:"var(--red)"}}>Tell us →</a></p>}
        </div>
      </section>

      {featured.length > 0 && (
        <section className="section section--tight placesec">
          <div className="wrap wrap--mid">
            <SecRule title="Featured in The Carnation" meta={featured.length + (featured.length === 1 ? " story" : " stories")} />
            <div className="feat-list">
              {featured.map((x) => (
                <a className="featrow" href={"#/article/" + x.slug} key={x.slug}>
                  <span className="featrow__date">{x.date}</span>
                  <div className="featrow__body">
                    <span className="featrow__cat">{x.category}</span>
                    <span className="featrow__t">{x.title}</span>
                    <span className="featrow__d">{x.dek}</span>
                  </div>
                  <span className="featrow__go arw">→</span>
                </a>
              ))}
            </div>
          </div>
        </section>
      )}
      <section className="section section--tint" style={{marginTop:"clamp(36px,5vw,64px)"}}>
        <div className="wrap">
          <SecRule title={"More in " + l.cat} meta="The Local Index" href="#/local-index" />
          <div className="dirlist">
            {related.length ? related.map((r) => (
              <a className="dirrow" href={"#/place/" + r.slug} key={r.slug}>
                <span className="dirrow__n">{r.name}</span>
                <span className="dirrow__note">{r.note}</span>
              </a>
            )) : <p className="note">No other listings in this category yet.</p>}
          </div>
        </div>
      </section>
    </main>
  );
}

/* ===================== EVENTS ===================== */
function EventsPage() {
  const D = C();
  const events = [...D.EVENTS].sort((a, b) => a.ts - b.ts);
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Public Life</div>
          <h1 className="phead__title">What's On in Alliance</h1>
          <p className="phead__dek">A curated calendar of what's worth showing up for in Alliance — gatherings, openings, markets, shows, and cultural moments. We list what fits the city and aligns with our pillars; promoted events are reviewed and approved, never simply bought.</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>
      <section className="section section--tight">
        <div className="wrap">
          <Reveal>
            <div className="ev-list rise">
              {events.map((e) => (
                <a className="ev" href={"#/event/" + e.slug} key={e.slug}>
                  <div className="ev__when">{e.dateLabel}</div>
                  <div className="ev__body">
                    <span className="ev__cat">{e.cat} · {e.venue}</span>
                    <span className="ev__t">{e.title}</span>
                    <span className="ev__d">{e.blurb}</span>
                  </div>
                  <span className="ev__go arw">→</span>
                </a>
              ))}
            </div>
          </Reveal>
        </div>
      </section>
      <section className="section section--tint section--tight">
        <div className="wrap wrap--mid">
          <SecRule title="Get your event in front of the city" meta="Three ways" />
          <div className="ev-cta">
            <div className="ev-cta__cell">
              <span className="ev-cta__k">Free</span>
              <span className="ev-cta__h">Submit an event</span>
              <p className="ev-cta__p">A market, a show, a meeting worth attending — send it our way and we'll help fill the room.</p>
              <a className="btn btn--line" href="#/submit">Submit an event <span className="arw">→</span></a>
            </div>
            <div className="ev-cta__cell">
              <span className="ev-cta__k">Promoted</span>
              <span className="ev-cta__h">Promote an event</span>
              <p className="ev-cta__p">Move yours to the top of the board, into the Dispatch, and the roundup.</p>
              <a className="btn btn--line" href="#/advertise">Promote an event <span className="arw">→</span></a>
            </div>
            <div className="ev-cta__cell ev-cta__cell--feat">
              <span className="ev-cta__k">Partner</span>
              <span className="ev-cta__h">Sponsor the Events Board</span>
              <p className="ev-cta__p">Put your name on the city's calendar as its presenting partner, all season.</p>
              <a className="btn btn--red" href="#/advertise">Sponsor the board <span className="arw">→</span></a>
            </div>
          </div>
          <p className="note" style={{marginTop:"clamp(20px,2.4vw,28px)", maxWidth:"64ch"}}>The board is curated. We list what fits Alliance and aligns with our pillars — and every promoted or sponsored placement is reviewed and approved, not simply purchased.</p>
        </div>
      </section>
    </main>
  );
}

function EventPage({ slug }) {
  const D = C();
  const e = D.byEvent(slug);
  useEffect(() => { window.scrollTo(0, 0); }, [slug]);
  if (!e) {
    return <main className="route"><section className="section"><div className="wrap wrap--narrow">
      <p className="note">That event could not be found. <a href="#/events" style={{color:"var(--red)"}}>Back to events →</a></p>
    </div></section></main>;
  }
  const others = D.EVENTS.filter((x) => x.slug !== slug).slice(0, 3);
  return (
    <main className="route art">
      <div className="wrap wrap--mid">
        <a className="backlink" href="#/events">← Events</a>
        <header className="art__head">
          <div className="art__cat">{e.cat} · {e.venue}</div>
          <h1 className="art__title">{e.title}</h1>
          <p className="art__dek">{e.blurb}</p>
          <div className="art__byline"><span>{e.dateLabel}</span><span>·</span><span>{e.venue}</span></div>
          <div className="art__actions"><ShareRow title={e.title} url={postUrl("event", e.slug)} /></div>
        </header>
      </div>
      <div className="wrap wrap--mid"><Cover variant={e.plate} tag={e.cat} slot={"cover:event:" + e.slug} className="art__cover" alt={e.title} /></div>
      <div className="wrap"><div className="art__body">
        <p><span className="art__dateline">{e.venue} —</span> {e.blurb} The Carnation keeps a running calendar of what's worth leaving the house for in Alliance; this is one of them.</p>
        <p>Details and exact dates can shift — confirm with the venue before you go. If you're hosting something that belongs on this calendar, we'd like to hear about it.</p>
        {e.spot && <p>Want the full story? <a href={"#/spotlight/" + e.spot} style={{color:"var(--red)"}}>Read our Spotlight on {e.title} →</a></p>}
        <div className="art__foot">
          <p className="note">Hosting an event downtown? <a href="#/submit" style={{color:"var(--red)"}}>Submit it to The Carnation →</a></p>
        </div>
      </div></div>
      <section className="section section--tint" style={{marginTop:"clamp(36px,5vw,64px)"}}>
        <div className="wrap">
          <SecRule title="More on the calendar" meta="All events" href="#/events" />
          <div className="ev-list">
            {others.map((x) => (
              <a className="ev" href={"#/event/" + x.slug} key={x.slug}>
                <div className="ev__when">{x.dateLabel}</div>
                <div className="ev__body">
                  <span className="ev__cat">{x.cat} · {x.venue}</span>
                  <span className="ev__t">{x.title}</span>
                </div>
                <span className="ev__go arw">→</span>
              </a>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

/* ===================== SAVED ===================== */
function SavedPage() {
  const D = C();
  useStore();
  const slugs = S().saved.list();
  const list = slugs.map((s) => D.bySlug(s)).filter(Boolean);
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Reading list</div>
          <h1 className="phead__title">Saved Stories</h1>
          <p className="phead__dek">The stories you've set aside to come back to. Saved in this browser — your list, kept private.</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>
      <section className="section section--tight">
        <div className="wrap">
          {list.length ? (
            <Reveal><div className="listgrid rise">{list.map((a) => <ArticleCard a={a} size="md" key={a.slug} />)}</div></Reveal>
          ) : (
            <div className="empty">
              <p className="empty__h">Nothing saved yet.</p>
              <p className="note">Tap <b>Save</b> on any story and it'll wait for you here.</p>
              <a className="btn btn--line" href="#/stories" style={{marginTop:"18px"}}>Browse all stories <span className="arw">→</span></a>
            </div>
          )}
        </div>
      </section>
    </main>
  );
}

/* ===================== 404 ===================== */
function NotFoundPage() {
  const D = C();
  return (
    <main className="route">
      <section className="section" style={{paddingTop:"clamp(48px,8vw,110px)"}}>
        <div className="wrap wrap--mid notfound">
          <div className="notfound__code">404</div>
          <h1 className="notfound__h">This page hasn't been written yet.</h1>
          <p className="notfound__p">The address you followed doesn't lead anywhere in The Carnation — a stale link, a typo, or a story that moved. Here's the way back.</p>
          <div className="notfound__links">
            <a className="btn btn--red" href="#/">Front page <span className="arw">→</span></a>
            <a className="btn btn--line" href="#/stories">All stories</a>
            <a className="btn btn--line" href="#/search">Search</a>
          </div>
          <div className="notfound__more">
            <span className="meta">Or pick up here</span>
            <div className="listgrid" style={{marginTop:"18px"}}>
              {D.latest(3).map((a) => <ArticleCard a={a} size="md" key={a.slug} />)}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

window.PlacePage = PlacePage;
window.EventsPage = EventsPage;
window.EventPage = EventPage;
window.SavedPage = SavedPage;
window.NotFoundPage = NotFoundPage;
