// IndieVertical — the project page (public showcase, role-aware).

function ivYoutubeId(url) {
  if (!url) return null;
  try {
    const u = url.includes("://") ? url : "https://" + url;
    const p = new URL(u);
    if (p.hostname === "youtu.be") return p.pathname.slice(1).split("?")[0];
    if (p.hostname.includes("youtube.com")) {
      if (p.pathname.startsWith("/shorts/")) return p.pathname.split("/")[2];
      if (p.pathname.startsWith("/embed/")) return p.pathname.split("/")[2];
      return p.searchParams.get("v");
    }
  } catch (_) {}
  return null;
}

function IvTrailer({ trailerUrl, trailerLabel }) {
  const [playing, setPlaying] = React.useState(false);
  const videoId = ivYoutubeId(trailerUrl);

  if (playing && videoId) {
    return (
      <div className="trailer">
        <iframe
          src={"https://www.youtube-nocookie.com/embed/" + videoId + "?autoplay=1&rel=0"}
          title="Trailer"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
          style={{ position:"absolute", inset:0, width:"100%", height:"100%", border:"none" }}
        />
      </div>
    );
  }

  if (trailerUrl || trailerLabel) {
    return (
      <div
        className="trailer"
        style={videoId ? { cursor: "pointer" } : undefined}
        onClick={videoId ? () => setPlaying(true) : undefined}
        role={videoId ? "button" : undefined}
        aria-label={videoId ? "Play trailer" : undefined}
        tabIndex={videoId ? 0 : undefined}
        onKeyDown={videoId ? (e) => { if (e.key === "Enter" || e.key === " ") setPlaying(true); } : undefined}
      >
        <span className="play"></span>
        <span className="trailer-label">{trailerLabel || trailerUrl}</span>
      </div>
    );
  }

  return (
    <div className="trailer" style={{ background: "var(--surface)" }}>
      <span className="empty-inline">No trailer yet.</span>
    </div>
  );
}

function IvProjectPage({ slug }) {
  const { state, api } = useStore();
  const g = ivGetGame(state, slug);
  const role = state.role;

  if (!g || (!g.owned && !IV_CATALOG[slug])) {
    return (
      <div className="pp dir-marquee">
        <IvHeader />
        <div style={{ padding: "60px 32px" }}>
          <IvEmptyState heading="This page does not exist" body="The game may have been unpublished, or the link is wrong." button="Browse games" href="#/browse" />
        </div>
        <IvFooter />
      </div>
    );
  }

  const owned = !!g.owned && role === "dev";
  const isDraft = g.projStatus === "draft";
  const isPending = g.projStatus === "pending";
  const saved = !!state.shortlist[slug];
  const socialLinks = g.socials
    ? [["X", g.socials.x], ["Bluesky", g.socials.bluesky], ["Instagram", g.socials.instagram], ["TikTok", g.socials.tiktok], ["Facebook", g.socials.facebook], ["LinkedIn", g.socials.linkedin], ["Linktree", g.socials.linktree]].filter(([, v]) => v)
    : null;
  const hasTraction = g.traction && (g.traction.wishlists || g.traction.discord || g.traction.social);
  const showTraction = hasTraction && (!g.tractionGated || role === "scout" || owned);

  const onMessage = () => {
    const id = api.openThreadForGame(g);
    ivGo("#/inbox/" + id);
  };

  return (
    <div className="pp dir-marquee">
      <IvHeader />

      {owned && isDraft && (
        <div className="pending is-draft">
          Draft preview — only you can see this page. Publish it from the editor when you are ready.
          <button type="button" className="demo-act" onClick={() => ivGo("#/dashboard/projects/" + slug)}>Back to editor</button>
        </div>
      )}
      {owned && isPending && (
        <div className="pending">
          Pending review — your public fields are already live while we take a look. This usually takes a day or two.
          <button type="button" className="demo-act" onClick={() => api.approveProject(slug)}>Demo: mark review complete</button>
        </div>
      )}

      <div className={"pp-banner " + g.art} style={g.keyArtUrl ? { backgroundImage: "url(" + g.keyArtUrl + ")", backgroundSize: "cover", backgroundPosition: "center" } : undefined}>
        <div className="scrim"></div>
        {owned && <a className="banner-edit" href={"#/dashboard/projects/" + slug}>Edit this page</a>}
        <div className="pp-banner-inner">
          <h1>{g.name}</h1>
          {g.hook && <p className="hook">{g.hook}</p>}
        </div>
      </div>

      <div className="pp-fold">
        <div>
          <IvTrailer trailerUrl={g.trailerUrl} trailerLabel={g.trailerLabel} />
        </div>

        <aside className="rail">
          <div className="badge-row">
            {g.status && <span className="badge">{g.status}</span>}
            {g.deal && <span className="badge">{g.deal}</span>}
            {g.demo && <span className="badge demo">Demo available</span>}
            {g.open && <span className="badge open">Open to conversations</span>}
          </div>

          {showTraction && (
            <div className="rail-card">
              <h4>Traction</h4>
              <div className="stat-grid">
                {g.traction.wishlists && <div className="stat"><div className="v">{g.traction.wishlists}</div><div className="l">Steam wishlists</div></div>}
                {g.traction.discord && <div className="stat"><div className="v">{g.traction.discord}</div><div className="l">Discord members</div></div>}
                {g.traction.social && <div className="stat"><div className="v">{g.traction.social}</div><div className="l">Social followers</div></div>}
              </div>
            </div>
          )}

          <div className="rail-card">
            <h4>Team</h4>
            <div className="team-rows">
              {g.studio && <div className="row"><span className="k">Studio</span><span className="val">{g.studio}</span></div>}
              {g.teamSize && <div className="row"><span className="k">Team size</span><span className="val">{g.teamSize}</span></div>}
              {g.location && <div className="row"><span className="k">Location</span><span className="val">{g.location}</span></div>}
              {g.targetRelease && <div className="row"><span className="k">Target release</span><span className="val">{g.targetRelease}</span></div>}
            </div>
            {owned && g.stats && (
              <div className="meta-line">Updated {g.updated} · {g.stats.views.toLocaleString()} page views (only you see this)</div>
            )}
          </div>

          <div className="rail-actions">
            {owned ? (
              <React.Fragment>
                <a className="btn btn-primary" href={"#/dashboard/projects/" + slug}>Edit this page</a>
                <a className="btn btn-secondary" href="#/dashboard">View stats</a>
                <p className="login-note">This is how your page looks to you. Scouts see the public fields plus anything set to publisher accounts only.</p>
              </React.Fragment>
            ) : role === "scout" ? (
              <React.Fragment>
                <button type="button" className={"btn " + (saved ? "btn-secondary" : "btn-primary")} onClick={() => api.toggleShortlist(slug, g.name)}>
                  {saved ? "✓ Saved — remove from shortlist" : "Save to shortlist"}
                </button>
                <button type="button" className="btn btn-secondary" onClick={onMessage}>Message Developer</button>
                <p className="login-note">Developers cannot see who saved their game. Your shortlist and notes are private.</p>
              </React.Fragment>
            ) : role === "dev" ? (
              <p className="login-note">You are signed in as a developer. Shortlists and messaging are for publisher and scout accounts.</p>
            ) : (
              <React.Fragment>
                <a className="btn btn-primary" href="#/signup">Save to shortlist</a>
                <a className="btn btn-secondary" href="#/signup">Message Developer</a>
                <p className="login-note">You need an account to save games or message developers. <a href="#/signup">Sign up free</a> or <a href="#/login">log in</a>.</p>
              </React.Fragment>
            )}
          </div>
        </aside>
      </div>

      <div className="pp-body">
        {g.about && g.about.length > 0 && (
          <section className="pp-section">
            <h2>About This Game</h2>
            {g.about.map((p, i) => <p key={i} className="body">{p}</p>)}
          </section>
        )}

        {g.shots && g.shots.length > 0 && (
          <section className="pp-section">
            <h2>Screenshots</h2>
            <div className="shots">
              {g.shots.map((s) => (
                <div key={s.label} className={"shot " + s.cls}><span>{s.label}</span></div>
              ))}
            </div>
          </section>
        )}

        {g.comps && g.comps.length > 0 && (
          <section className="pp-section">
            <h2>Games Like This</h2>
            <div className="comp-row">
              {g.comps.map((c) => (
                <div key={c.t} className="comp">
                  <div className="c-t">{c.t}</div>
                  {c.d && <div className="c-d">{c.d}</div>}
                </div>
              ))}
            </div>
          </section>
        )}

        {(g.deal || g.targetRelease || (g.wants && g.wants.length > 0) || g.funding) && (
          <section className="pp-section">
            <h2>Deal Details</h2>
            <div className="deal-grid">
              {g.deal && (
                <div className="deal-item">
                  <div className="k">Deal type</div>
                  <div className="v">{g.deal}</div>
                </div>
              )}
              {g.targetRelease && (
                <div className="deal-item">
                  <div className="k">Target release</div>
                  <div className="v">{g.targetRelease}</div>
                </div>
              )}
              {g.wants && g.wants.length > 0 && (
                <div className="deal-item" style={{ gridColumn: "1 / -1" }}>
                  <div className="k">What we want from a partner</div>
                  <div className="want-chips">
                    {g.wants.map((w) => <span key={w} className="chip">{w}</span>)}
                  </div>
                </div>
              )}
              {g.funding && (
                <div className="deal-item" style={{ gridColumn: "1 / -1" }}>
                  <div className="k">Funding range</div>
                  {g.fundingGated && !owned
                    ? <IvGate title="Funding range" value={g.funding} role={role} />
                    : <div className="v">{g.funding}{owned && g.fundingGated ? " · shown to publisher accounts only" : ""}</div>}
                </div>
              )}
            </div>
          </section>
        )}

        {g.contact && (
          <section className="pp-section">
            <h2>Get in Touch</h2>
            {g.contactGated && !owned
              ? <IvGate title="Contact details" value={g.contact} role={role} />
              : <p className="body" style={{ fontWeight: 600 }}>{g.contact}{owned && g.contactGated ? " · shown to publisher accounts only" : ""}</p>}
          </section>
        )}

        {(() => {
          const labels = (g.links && g.links.length > 0) ? g.links : (socialLinks || []).map(([l]) => l);
          if (labels.length === 0) return null;
          return (
            <section className="pp-section">
              <h2>Links</h2>
              <div className="links-row">
                {labels.map((l) => <span key={l} className="link-chip">{l}</span>)}
              </div>
            </section>
          );
        })()}

        {g.pastWork && g.pastWork.length > 0 && (
          <section className="pp-section">
            <h2>Past Work</h2>
            <div className="past-rows">
              {g.pastWork.map((w) => (
                <div key={w.t} className="past-row">
                  <span className="t">{w.t}</span><span className="m">{w.m}</span><span className="m">{w.y}</span>
                </div>
              ))}
            </div>
          </section>
        )}

        {g.teamAbout && (
          <section className="pp-section">
            <h2>About the Team</h2>
            <p className="body">{g.teamAbout}</p>
            {g.members && g.members.length > 0 && (
              <div className="member-row">
                {g.members.map((m) => (
                  <div key={m.n} className="member">
                    <span className="m-av">{m.i}</span>
                    <span><span className="m-n">{m.n}</span><span className="m-r">{m.r}</span></span>
                  </div>
                ))}
              </div>
            )}
          </section>
        )}

        {g.updated && <div className="updated-line">Updated {g.updated}</div>}
      </div>

      <IvFooter />
    </div>
  );
}

Object.assign(window, { IvProjectPage });
