// IndieVertical — shared UI: icons, header, footer, cards, filter bar, sidebar, gates, role bar.

const IvLogoMark = ({ size = 24 }) => (
  <svg className="pp-logo-mark" viewBox="0 0 44 56" xmlns="http://www.w3.org/2000/svg" style={{ height: size, width: "auto" }}>
    <rect width="44" height="56" rx="10" fill="#c14a09"/>
    <path d="M6,9 L38,9 L30,47 L14,47 Z" fill="white"/>
  </svg>
);

const IvLock = () => (
  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="4" y="11" width="16" height="10" rx="2"></rect>
    <path d="M8 11V7a4 4 0 0 1 8 0v4"></path>
  </svg>
);

const IvSearch = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
    <circle cx="11" cy="11" r="7"></circle>
    <path d="M21 21l-4.3-4.3"></path>
  </svg>
);

// ---------- header ----------
function IvHeader() {
  const { state, api } = useStore();
  const route = useRoute();
  const role = state.role;
  const loggedIn = role !== "visitor";
  const user = role === "dev" ? IV_USERS.dev : IV_USERS.scout;
  const unread = ivUnreadCount(state, role);
  const on = (p) => (route.page === p ? "on" : "");
  return (
    <header className="pp-header">
      <a className="pp-logo" href="#/"><IvLogoMark size={24} />IndieVertical</a>
      <nav className="pp-nav">
        <a href="#/browse" className={on("browse")} aria-current={on("browse") ? "page" : undefined}>Browse Games</a>
        {!loggedIn && <a href="#/developers" className={on("developers")} aria-current={on("developers") ? "page" : undefined}>For Developers</a>}
        {!loggedIn && <a href="#/about" className={on("about")} aria-current={on("about") ? "page" : undefined}>About</a>}
        <a href="#/blog" className={on("blog")} aria-current={on("blog") ? "page" : undefined}>Blog</a>
        <a href="#/resources" className={on("resources")} aria-current={on("resources") ? "page" : undefined}>Resources</a>
        {loggedIn && <a href="#/dashboard" className={on("dashboard")} aria-current={on("dashboard") ? "page" : undefined}>Dashboard</a>}
        {loggedIn && (
          <a href="#/inbox" className={on("inbox")} aria-current={on("inbox") ? "page" : undefined} style={{ position: "relative" }}>
            Inbox
            {unread > 0 && <span style={{ position: "absolute", top: -2, right: -9, width: 7, height: 7, borderRadius: "50%", background: "var(--warm)" }}></span>}
          </a>
        )}
        {loggedIn ? (
          <span className="nav-auth">
            <span style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--ink)", color: "var(--bg)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800 }} title={user.name}>{user.initials}</span>
            <a className="nav-logout" onClick={(e) => { e.preventDefault(); api.logout(); ivGo("#/"); }} href="#/">Log Out</a>
          </span>
        ) : (
          <span className="nav-auth">
            <a className="nav-login" href="#/login">Log In</a>
            <a className="nav-signup" href="#/signup">Sign Up</a>
          </span>
        )}
      </nav>
    </header>
  );
}

// ---------- footer ----------
function IvFooter() {
  return (
    <footer className="ftr">
      <span className="ftr-brand" style={{ display: "flex", alignItems: "center", gap: 6 }}><IvLogoMark size={16} />IndieVertical</span>
      <a href="#/browse">Browse</a>
      <a href="#/signup">Make a Page</a>
      <a href="#/about">About</a>
      <a href="#/contact">Contact</a>
      <a href="#/sponsor">Sponsors</a>
      <a href="#/blog">Blog</a>
      <a href="#/resources">Resources</a>
      <a href="#/faq">FAQ</a>
      <a href="#/terms">Terms of Use</a>
      <a href="#/privacy">Privacy Policy</a>
    </footer>
  );
}

// ---------- game card ----------
function IvGameCard({ g, variant, maxBadges }) {
  const badges = [];
  if (g.status) badges.push(<span key="s" className="badge">{g.status}</span>);
  if (g.deal) badges.push(<span key="d" className="badge">{g.deal}</span>);
  if (g.demo) badges.push(<span key="demo" className="badge demo">Demo available</span>);
  else if (g.open) badges.push(<span key="o" className="badge open">Open to conversations</span>);
  return (
    <a className="cardlink" href={"#/game/" + g.slug}>
      <article className={"gcard" + (variant ? " is-" + variant : "")}>
        <div className={"gc-art " + g.art} style={g.keyArtUrl ? { backgroundImage: "url(" + g.keyArtUrl + ")", backgroundSize: "cover", backgroundPosition: "center" } : undefined}>
          <span className="gc-name">{g.name}</span>
        </div>
        <div className="gc-body">
          <p className="gc-hook">{g.hook}</p>
          <div className="gc-tags">{(g.genres || []).join(" · ")}</div>
          <div className="badge-row">{badges.slice(0, maxBadges || 3)}</div>
        </div>
      </article>
    </a>
  );
}

// ---------- game row (list layout for browse + promoted) ----------
const IvStar = () => (
  <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" stroke="none">
    <path d="M12 2l3.1 6.6 7 .9-5.2 4.9 1.4 7-6.3-3.5L5.7 21.4l1.4-7L1.9 9.5l7-.9z"></path>
  </svg>
);

function IvGameRow({ g, variant, flags }) {
  const badges = [];
  if (g.status) badges.push(<span key="s" className="badge">{g.status}</span>);
  if (g.deal) badges.push(<span key="d" className="badge">{g.deal}</span>);
  if (g.demo) badges.push(<span key="demo" className="badge demo">Demo available</span>);
  if (g.open) badges.push(<span key="o" className="badge open">Open to conversations</span>);
  return (
    <a className="rowlink" href={"#/game/" + g.slug}>
      <article className={"grow" + (variant ? " is-" + variant : "")}>
        <div className={"gr-art " + g.art} style={g.keyArtUrl ? { backgroundImage: "url(" + g.keyArtUrl + ")", backgroundSize: "cover", backgroundPosition: "center" } : undefined}></div>
        <div>
          <div className="gr-name-row">
            <span className="gr-name">{g.name}</span>
            {flags && g.editorsPick && <span className="gr-flag cool"><IvStar /> Editor's Pick</span>}
          </div>
          <p className="gr-hook">{g.hook}</p>
          <div className="gr-tags">
            {(g.genres || []).join(" · ")}
            {g.platforms && g.platforms.length > 0 ? " · " + g.platforms.join(", ") : ""}
          </div>
          <div className="badge-row">{badges}</div>
        </div>
        <div className="gr-meta">
          {g.studio && <span className="gm-k">{g.studio}</span>}
          {g.location && <span>{g.location}</span>}
          {g.targetRelease && <span>Target: {g.targetRelease}</span>}
        </div>
      </article>
    </a>
  );
}

// ---------- dropdown ----------
function IvDrop({ label, value, options, onChange, allLabel }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const triggerRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === "Escape") { setOpen(false); if (triggerRef.current) triggerRef.current.focus(); } };
    document.addEventListener("mousedown", close);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", close); document.removeEventListener("keydown", onKey); };
  }, [open]);
  const set = value != null && value !== "";
  return (
    <span className="dd" ref={ref}>
      <button type="button" ref={triggerRef} className={"fdrop" + (set ? " set" : "")} aria-haspopup="listbox" aria-expanded={open} onClick={() => setOpen(!open)}>
        {set ? label + ": " + value : label} <span className="car">▼</span>
      </button>
      {open && (
        <span className="dd-menu">
          <button type="button" className={"dd-opt" + (!set ? " sel" : "")} onClick={() => { onChange(null); setOpen(false); }}>
            {allLabel || "All"}
          </button>
          {options.map((o) => (
            <button type="button" key={o} className={"dd-opt" + (value === o ? " sel" : "")} onClick={() => { onChange(o); setOpen(false); }}>
              {o}
            </button>
          ))}
        </span>
      )}
    </span>
  );
}

// ---------- filter bar (live) ----------
const IV_EMPTY_FILTERS = { q: "", genre: null, platform: null, status: null, deal: null, demo: false, open: false };

function ivCountFilters(f) {
  let n = 0;
  if (f.q.trim()) n++;
  ["genre", "platform", "status", "deal"].forEach((k) => { if (f[k]) n++; });
  if (f.demo) n++;
  if (f.open) n++;
  return n;
}

function ivApplyFilters(games, f) {
  const q = f.q.trim().toLowerCase();
  return games.filter((g) => {
    if (q) {
      const hay = (g.name + " " + g.hook + " " + (g.genres || []).join(" ") + " " + (g.studio || "")).toLowerCase();
      if (!hay.includes(q)) return false;
    }
    if (f.genre && !(g.genres || []).includes(f.genre)) return false;
    if (f.platform && !(g.platforms || []).includes(f.platform)) return false;
    if (f.status && g.status !== f.status) return false;
    if (f.deal && g.deal !== f.deal) return false;
    if (f.demo && !g.demo) return false;
    if (f.open && !(g.open || g.demo)) return false;
    return true;
  });
}

function IvFilterBar({ filters, setFilters }) {
  const f = filters;
  const set = (patch) => setFilters({ ...f, ...patch });
  const active = ivCountFilters(f);
  return (
    <div className="fbar">
      <label className="fsearch">
        <IvSearch />
        <input
          type="text"
          value={f.q}
          placeholder="Search games…"
          onChange={(e) => set({ q: e.target.value })}
        />
      </label>
      <IvDrop label="Genre" value={f.genre} options={IV_GENRES} onChange={(v) => set({ genre: v })} allLabel="All genres" />
      <IvDrop label="Platform" value={f.platform} options={IV_PLATFORMS} onChange={(v) => set({ platform: v })} allLabel="All platforms" />
      <IvDrop label="Dev Status" value={f.status} options={IV_DEV_STATUSES} onChange={(v) => set({ status: v })} allLabel="Any status" />
      <IvDrop label="Deal Type" value={f.deal} options={IV_DEAL_TYPES} onChange={(v) => set({ deal: v })} allLabel="Any deal type" />
      <button type="button" className={"ftoggle" + (f.demo ? "" : " off")} onClick={() => set({ demo: !f.demo })}>
        {f.demo ? "✓ " : ""}Demo Available
      </button>
      <button type="button" className={"ftoggle cool-t" + (f.open ? "" : " off")} onClick={() => set({ open: !f.open })}>
        {f.open ? "✓ " : ""}Open to Conversations
      </button>
      {active > 0 && (
        <button type="button" className="fclear" onClick={() => setFilters({ ...IV_EMPTY_FILTERS })}>
          Clear Filters
        </button>
      )}
    </div>
  );
}

// ---------- sidebar ----------
function IvSidebar({ items }) {
  return (
    <aside className="side">
      {items.map((it) => (
        <a key={it.label} className={"s-item" + (it.on ? " on" : "")} href={it.href}>
          {it.label}
          {it.dot && <span className="dot"></span>}
        </a>
      ))}
    </aside>
  );
}

// ---------- gated field ----------
function IvGate({ title, value, role }) {
  if (role === "scout") {
    return (
      <div className="gate-open">
        <span className="lock"><IvLock /></span>
        <div>
          <div className="g-v">{value}</div>
          <div className="g-w">Shared with publisher accounts only — please keep it that way.</div>
        </div>
      </div>
    );
  }
  return (
    <div className="gate">
      <span className="lock"><IvLock /></span>
      <div>
        <div className="g-t">{title}</div>
        <div className="g-d">
          This is only shown to publisher accounts.{" "}
          <a href="#/signup">Sign in with a publisher account</a> to view it.
        </div>
      </div>
    </div>
  );
}

// ---------- visibility toggle (interactive) ----------
function IvVisToggle({ gated, onChange }) {
  return (
    <div className="vtg">
      <div className="vtg-btns">
        <button type="button" className={"vb" + (!gated ? " on" : "")} onClick={() => onChange(false)}>Public</button>
        <button type="button" className={"vb" + (gated ? " on" : "")} onClick={() => onChange(true)}>Publisher accounts only</button>
      </div>
      <span className="vtg-exp">
        {gated
          ? "Only accounts that signed up as a publisher or scout can see this. People who are not logged in cannot."
          : "Anyone visiting the site can see this, even people who are not logged in."}
      </span>
    </div>
  );
}

// ---------- empty state ----------
function IvEmptyState({ heading, body, button, onClick, href, reassure, children }) {
  return (
    <div className="estate">
      <h3>{heading}</h3>
      {body && <p>{body}</p>}
      {children}
      {button && (
        href
          ? <a className="btn btn-primary" href={href}>{button}</a>
          : <button type="button" className="btn btn-primary" onClick={onClick}>{button}</button>
      )}
      {reassure && <span className="e-reassure">{reassure}</span>}
    </div>
  );
}

// ---------- role switcher (demo chrome) ----------
function IvRoleBar() {
  const { state, api } = useStore();
  const r = state.role;
  const pick = (role) => {
    if (role === r) return;
    api.setRole(role);
    if (role === "visitor" && (location.hash.includes("dashboard") || location.hash.includes("inbox"))) ivGo("#/");
  };
  return (
    <div className="rolebar">
      <span className="rb-l">View as</span>
      <button type="button" className={r === "visitor" ? "on" : ""} aria-pressed={r === "visitor"} onClick={() => pick("visitor")}>Visitor</button>
      <button type="button" className={r === "dev" ? "on" : ""} aria-pressed={r === "dev"} onClick={() => pick("dev")}>Developer</button>
      <button type="button" className={r === "scout" ? "on" : ""} aria-pressed={r === "scout"} onClick={() => pick("scout")}>Scout</button>
      <button type="button" className="rb-reset" aria-label="Reset demo data" title="Reset all demo data" onClick={() => api.resetDemo()}>↺</button>
    </div>
  );
}

Object.assign(window, {
  IvLock, IvSearch, IvHeader, IvFooter, IvGameCard, IvGameRow, IvDrop, IvFilterBar,
  IV_EMPTY_FILTERS, ivCountFilters, ivApplyFilters,
  IvSidebar, IvGate, IvVisToggle, IvEmptyState, IvRoleBar,
});
