// Public-facing screens: Landing, Profile, Project, Explore
const { PEOPLE, FEED, COLLECTIONS } = window.DATA;

// =========================================================================
// LANDING
// =========================================================================
function Landing({ go }) {
  const featured = PEOPLE.slice(0, 6);
  return (
    <div className="landing">
      {/* Top marquee bar */}
      <div className="landing-strip">
        <span>A quieter place for professional identity</span>
        <span className="strip-dot">·</span>
        <span>Now in public beta</span>
      </div>

      {/* Hero */}
      <section className="hero">
        <div className="hero-inner">
          <h1 className="hero-title">
            <span className="hero-line">A folio,</span>
            <span className="hero-line"><em>not a feed.</em></span>
          </h1>
          <p className="hero-sub">
            Folio Index is a calm, typography-first home for your work, your career, and the people you make things with.
          </p>
          <div className="hero-cta">
            <Button variant="primary" onClick={() => go("/onboarding")} icon={I.arrow}>Claim your folio</Button>
            <Button variant="ghost" onClick={() => go("/u/marin")}>See an example</Button>
          </div>
          <div className="hero-meta">
            <span>folio.index/<span className="mono">marin</span></span>
            <span className="strip-dot">·</span>
            <span>{PEOPLE.length.toLocaleString()}+ profiles</span>
            <span className="strip-dot">·</span>
            <span>No ads, no algorithm</span>
          </div>
        </div>

        {/* Floating example card */}
        <div className="hero-card" onClick={() => go("/u/marin")}>
          <div className="hero-card-banner" style={{ background: "linear-gradient(135deg,#E6D8C9,#D85A3A)" }} />
          <div className="hero-card-body">
            <Avatar person={PEOPLE[0]} size={56} ring />
            <div className="hero-card-meta">
              <h4>Marin Solberg</h4>
              <p>Independent Designer · Oslo</p>
            </div>
            <div className="hero-card-tags">
              <span className="dot dot-green" />
              <span>Open to projects · Aug</span>
            </div>
          </div>
          <div className="hero-card-grid">
            <div style={{ background: "linear-gradient(135deg,#E6D8C9,#D85A3A)" }} />
            <div style={{ background: "linear-gradient(135deg,#1B1B1B,#3A3A3A)" }} />
            <div style={{ background: "linear-gradient(135deg,#2E4B3C,#7A9A82)" }} />
          </div>
        </div>
      </section>

      {/* Feature row */}
      <section className="features">
        <div className="features-grid">
          {[
            { kicker: "Profile", title: "A single page that reads like a résumé and a portfolio at once.", body: "Work history, projects, side projects, education and writing — all in one calm document." },
            { kicker: "Discovery", title: "Find people by what they do, not by what they post.", body: "Browse by skill, city, and availability. Curated collections, no engagement-bait." },
            { kicker: "Editor", title: "Slash-command editor that gets out of your way.", body: "Markdown, embeds, image grids, video. Auto-saves. Drafts and scheduling." },
          ].map((f, i) => (
            <article key={i} className="feature-card">
              <div className="feature-kicker">{String(i + 1).padStart(2, "0")} · {f.kicker}</div>
              <h3>{f.title}</h3>
              <p>{f.body}</p>
            </article>
          ))}
        </div>
      </section>

      {/* Featured creators */}
      <section className="section-wrap">
        <header className="block-h">
          <div>
            <div className="kicker">Featured this week</div>
            <h2>People to know</h2>
          </div>
          <button className="link-arrow" onClick={() => go("/explore")}>Explore all {I.arrow}</button>
        </header>

        <div className="people-grid">
          {featured.map((p) => (
            <article key={p.handle} className="people-card" onClick={() => go(`/u/${p.handle}`)}>
              <div className="people-card-top">
                <Avatar person={p} size={48} />
                <div>
                  <div className="people-card-name">{p.name}</div>
                  <div className="people-card-role">{p.role}</div>
                </div>
              </div>
              <p className="people-card-bio">{p.bio}</p>
              <div className="people-card-foot">
                <span className="mono">@{p.handle}</span>
                <span>{p.location}</span>
              </div>
            </article>
          ))}
        </div>
      </section>

      {/* Quote / editorial pull */}
      <section className="pull">
        <blockquote>
          <span className="quote-mark">“</span>
          The internet used to be a place you built things on. Folio Index feels like that again.
        </blockquote>
        <cite>— Field Notes, issue 11</cite>
      </section>

      {/* Closing CTA */}
      <section className="closer">
        <h2>Begin your folio.</h2>
        <p>Free forever for one profile. No tracking, no ads.</p>
        <Button variant="primary" size="lg" onClick={() => go("/onboarding")} icon={I.arrow}>Claim your URL</Button>
        <div className="closer-url">folio.index/<span className="mono closer-blink">your-name</span></div>
      </section>

      <footer className="foot">
        <div className="foot-l">
          <div className="logo-mark"><LogoMark /></div>
          <span>Folio Index</span>
        </div>
        <div className="foot-cols">
          <div><strong>Product</strong><a>Profiles</a><a>Projects</a><a>Editor</a></div>
          <div><strong>Company</strong><a>About</a><a>Careers</a><a>Press</a></div>
          <div><strong>Legal</strong><a>Terms</a><a>Privacy</a><a>Acceptable use</a></div>
        </div>
        <div className="foot-r">Made carefully. © 2026</div>
      </footer>
    </div>
  );
}

function LogoMark({ size = 18 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden>
      <rect x="3" y="3" width="18" height="18" rx="3" fill="none" stroke="currentColor" strokeWidth="1.6" />
      <path d="M8 8h8M8 12h5M8 16h7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}

// =========================================================================
// PROFILE
// =========================================================================
function Profile({ handle, go }) {
  const p = window.byHandle(handle);
  const [following, setFollowing] = useState(false);
  const [tab, setTab] = useState("work");

  return (
    <div className="profile">
      <div className="profile-banner" style={{ background: `linear-gradient(135deg, ${p.accent}33, ${p.accent}10)` }}>
        <div className="profile-banner-stripes" />
      </div>

      <div className="profile-shell">
        <header className="profile-head">
          <div className="profile-head-l">
            <Avatar person={p} size={112} ring />
            <div className="profile-id">
              <h1>{p.name}</h1>
              <div className="profile-handle">
                <span className="mono">folio.index/{p.handle}</span>
                <span className="strip-dot">·</span>
                <span>{p.pronouns}</span>
              </div>
              <div className="profile-meta">
                <span>{I.pin} {p.location}</span>
                {p.available && (
                  <span className="avail">
                    <span className="dot dot-green" />
                    {p.available}
                  </span>
                )}
              </div>
            </div>
          </div>
          <div className="profile-head-r">
            <Button variant={following ? "ghost" : "primary"} onClick={() => setFollowing(!following)} icon={following ? I.check : I.plus}>
              {following ? "Following" : "Follow"}
            </Button>
            <Button variant="ghost" icon={I.message}>Message</Button>
            <button className="icon-btn" aria-label="More">{I.more}</button>
          </div>
        </header>

        <section className="profile-bio">
          <p>{p.bio}</p>
          <div className="profile-links">
            {p.links?.map((l, i) => (
              <a key={i} className="prof-link">{l.label} {I.ext}</a>
            ))}
          </div>
        </section>

        <div className="profile-stats">
          <Stat value={p.followers?.toLocaleString()} label="Followers" />
          <Stat value={p.following?.toLocaleString()} label="Following" />
          <Stat value={p.appreciations?.toLocaleString()} label="Appreciations" />
          <Stat value={p.projects?.length || 0} label="Projects" />
        </div>

        <nav className="profile-tabs">
          {[
            ["work", "Work"],
            ["projects", "Projects"],
            ["side", "Side"],
            ["writing", "Writing"],
            ["collections", "Collections"],
          ].map(([k, v]) => (
            <button key={k} className={`tab${tab === k ? " tab-active" : ""}`} onClick={() => setTab(k)}>
              {v}
            </button>
          ))}
        </nav>

        {tab === "work" && (
          <div className="profile-cols">
            <div className="profile-col-l">
              <SectionH>Work history</SectionH>
              <ol className="timeline">
                {p.work?.map((w, i) => (
                  <li key={i} className="timeline-item">
                    <div className="timeline-yrs mono">{w.start} — {w.end}</div>
                    <div className="timeline-body">
                      <div className="timeline-role">{w.role}</div>
                      <div className="timeline-org">{w.company}</div>
                      {w.note && <p>{w.note}</p>}
                    </div>
                  </li>
                ))}
              </ol>

              <SectionH>Education</SectionH>
              <ol className="timeline">
                {p.education?.map((e, i) => (
                  <li key={i} className="timeline-item">
                    <div className="timeline-yrs mono">{e.start} — {e.end}</div>
                    <div className="timeline-body">
                      <div className="timeline-role">{e.program}</div>
                      <div className="timeline-org">{e.school}</div>
                    </div>
                  </li>
                ))}
              </ol>
            </div>

            <aside className="profile-col-r">
              <SectionH>Skills</SectionH>
              <div className="chip-row">
                {p.skills?.map((s) => <span key={s} className="chip chip-static">{s}</span>)}
              </div>

              <SectionH>Side projects</SectionH>
              <ul className="side-list">
                {p.sideProjects?.map((s, i) => (
                  <li key={i}>
                    <div className="side-name">{s.name} <span className="mono side-year">{s.year}</span></div>
                    <div className="side-note">{s.note}</div>
                  </li>
                ))}
              </ul>

              <SectionH>Now</SectionH>
              <p className="now-note">
                Reading <em>The Tacit Dimension</em>. Drinking too much coffee. Looking at letters.
              </p>
            </aside>
          </div>
        )}

        {tab === "projects" && (
          <div className="projects-grid">
            {p.projects?.map((pr) => (
              <article key={pr.id} className="project-card" onClick={() => go(`/p/${p.handle}/${pr.id}`)}>
                <Cover background={pr.cover} ratio="4/3" />
                <div className="project-meta">
                  <div className="project-title">{pr.title}</div>
                  <div className="project-sub mono">{pr.tag} · {pr.year}</div>
                </div>
              </article>
            ))}
          </div>
        )}

        {tab === "side" && (
          <div className="empty-pane">
            <p>Side projects appear here.</p>
            <ul className="side-list side-list-lg">
              {p.sideProjects?.map((s, i) => (
                <li key={i}>
                  <div className="side-name">{s.name} <span className="mono side-year">{s.year}</span></div>
                  <div className="side-note">{s.note}</div>
                </li>
              ))}
            </ul>
          </div>
        )}

        {tab === "writing" && (
          <div className="empty-pane">
            <ol className="writing-list">
              <li>
                <div className="writing-date mono">May 2025</div>
                <div className="writing-title">On briefs that breathe</div>
                <p>Why the best clients give you less, not more — and how to ask for it.</p>
              </li>
              <li>
                <div className="writing-date mono">Mar 2025</div>
                <div className="writing-title">A type specimen for myself</div>
                <p>Drafting a personal specimen sheet. What it changed about how I read my own work.</p>
              </li>
              <li>
                <div className="writing-date mono">Jan 2025</div>
                <div className="writing-title">Studio of one</div>
                <p>Notes from a year of working alone, on purpose.</p>
              </li>
            </ol>
          </div>
        )}

        {tab === "collections" && (
          <div className="collections-grid">
            {COLLECTIONS.filter((c) => c.curator === p.handle).map((c, i) => (
              <article key={i} className="coll-card">
                <div className="coll-stack">
                  <div className="coll-thumb" style={{ background: "linear-gradient(135deg,#E6D8C9,#D85A3A)" }} />
                  <div className="coll-thumb" style={{ background: "linear-gradient(135deg,#1B1B1B,#3A3A3A)" }} />
                  <div className="coll-thumb" style={{ background: "linear-gradient(135deg,#2E4B3C,#7A9A82)" }} />
                </div>
                <div className="coll-meta">
                  <div className="coll-title">{c.title}</div>
                  <div className="coll-count mono">{c.count} items</div>
                </div>
              </article>
            ))}
            {COLLECTIONS.filter((c) => c.curator === p.handle).length === 0 && (
              <p className="muted">No collections yet.</p>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// =========================================================================
// PROJECT DETAIL
// =========================================================================
function ProjectPage({ handle, projectId, go }) {
  const p = window.byHandle(handle);
  const pr = p.projects?.find((x) => x.id === projectId) || p.projects?.[0];
  if (!pr) return null;
  return (
    <div className="project-page">
      <div className="project-page-bar">
        <button className="back-btn" onClick={() => go(`/u/${handle}`)}>{I.back} Back to {p.name}</button>
        <div className="proj-share">
          <Button variant="ghost" size="sm" icon={I.heart}>Appreciate</Button>
          <Button variant="ghost" size="sm">Save</Button>
        </div>
      </div>

      <article className="project-article">
        <header className="proj-header">
          <div className="kicker mono">{pr.tag} · {pr.year}</div>
          <h1>{pr.title}</h1>
          <p className="proj-lede">
            A complete identity for a small publisher of slow software. Built around a custom serif, a restrained color system, and a rhythm meant to be read.
          </p>
          <div className="proj-credits">
            <div><span className="mono kicker">Client</span><span>Onsa Publishing</span></div>
            <div><span className="mono kicker">Role</span><span>Identity · Type · Art Direction</span></div>
            <div><span className="mono kicker">Year</span><span>{pr.year}</span></div>
            <div><span className="mono kicker">Partners</span><span>Råd Studio</span></div>
          </div>
        </header>

        <div className="proj-hero" style={{ background: pr.cover }}>
          <span className="proj-hero-label mono">cover · 16/9</span>
        </div>

        <div className="proj-prose">
          <p>The brief asked for an identity that would carry a publisher into its next decade — confident, quiet, and recognizable in the way a serif is recognizable. The result is a single typeface family in three optical sizes, a palette of two warm neutrals, and a wordmark that reads as a small piece of writing.</p>
          <h2>Marks</h2>
          <p>The wordmark sits between handwriting and bookprinting. Its terminals are flat where most are rounded, and its counter shapes were drawn to survive at 6pt as much as at 600pt.</p>
        </div>

        <div className="proj-grid-2">
          <div className="proj-img" style={{ background: "linear-gradient(135deg,#1B1B1B,#3A3A3A)" }}>
            <span className="proj-hero-label mono">wordmark · still</span>
          </div>
          <div className="proj-img" style={{ background: "linear-gradient(135deg,#E6D8C9,#D85A3A)" }}>
            <span className="proj-hero-label mono">colorway · still</span>
          </div>
        </div>

        <div className="proj-prose">
          <h2>System</h2>
          <p>Beyond the mark, the system extends into a three-grid layout, a small set of editorial rules, and a single, generous margin that is the most important decision in the whole document.</p>
        </div>

        <div className="proj-img proj-img-wide" style={{ background: "linear-gradient(135deg,#2E4B3C,#7A9A82)" }}>
          <span className="proj-hero-label mono">spread · wide</span>
        </div>

        <footer className="proj-footer">
          <div className="proj-foot-author" onClick={() => go(`/u/${handle}`)}>
            <Avatar person={p} size={56} />
            <div>
              <div className="muted-l mono">A project by</div>
              <div className="proj-foot-name">{p.name}</div>
              <div className="proj-foot-role">{p.role} · {p.location}</div>
            </div>
            <Button variant="primary" size="sm" icon={I.plus}>Follow</Button>
          </div>
          <div className="proj-foot-actions">
            <Button variant="ghost" icon={I.heart}>1,204 appreciations</Button>
            <Button variant="ghost">Share</Button>
          </div>
        </footer>
      </article>
    </div>
  );
}

// =========================================================================
// EXPLORE
// =========================================================================
function Explore({ go }) {
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("All");
  const [view, setView] = useState("grid");
  const filters = ["All", "Design", "Engineering", "Writing", "Photography", "Founders"];

  const results = PEOPLE.filter((p) =>
    (q === "" || p.name.toLowerCase().includes(q.toLowerCase()) || p.role.toLowerCase().includes(q.toLowerCase()) || p.handle.includes(q.toLowerCase()))
  );

  return (
    <div className="explore">
      <header className="explore-head">
        <div className="kicker">Explore</div>
        <h1>People making good things.</h1>
        <p className="explore-lede">Curated weekly. {PEOPLE.length} of {(12480).toLocaleString()} profiles below.</p>

        <div className="explore-bar">
          <div className="search">
            {I.search}
            <input
              placeholder="Search by name, skill, company, city…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
            <kbd className="mono">⌘K</kbd>
          </div>
        </div>

        <div className="explore-filters">
          <div className="chip-row">
            {filters.map((f) => (
              <Chip key={f} active={filter === f} onClick={() => setFilter(f)}>{f}</Chip>
            ))}
          </div>
          <div className="view-toggle">
            <button className={view === "grid" ? "on" : ""} onClick={() => setView("grid")} aria-label="Grid">{I.grid}</button>
            <button className={view === "list" ? "on" : ""} onClick={() => setView("list")} aria-label="List">{I.list}</button>
          </div>
        </div>
      </header>

      {view === "grid" ? (
        <div className="explore-grid">
          {results.map((p) => (
            <article key={p.handle} className="explore-card" onClick={() => go(`/u/${p.handle}`)}>
              <div className="explore-card-banner" style={{ background: `linear-gradient(135deg, ${p.accent}, ${shade(p.accent, -30)})` }} />
              <div className="explore-card-body">
                <Avatar person={p} size={56} ring />
                <h3>{p.name}</h3>
                <div className="explore-card-role">{p.role}</div>
                <div className="explore-card-loc">{p.location}</div>
                {p.available && (
                  <div className="explore-card-avail">
                    <span className="dot dot-green" /> {p.available}
                  </div>
                )}
              </div>
            </article>
          ))}
        </div>
      ) : (
        <div className="explore-list">
          {results.map((p) => (
            <div key={p.handle} className="explore-row" onClick={() => go(`/u/${p.handle}`)}>
              <Avatar person={p} size={44} />
              <div className="row-name-col">
                <div className="row-name">{p.name}</div>
                <div className="row-handle mono">@{p.handle}</div>
              </div>
              <div className="row-role">{p.role}</div>
              <div className="row-loc">{p.location}</div>
              <div className="row-avail">{p.available || "—"}</div>
              <Button variant="ghost" size="sm">View</Button>
            </div>
          ))}
        </div>
      )}

      <section className="explore-collections">
        <header className="block-h">
          <div>
            <div className="kicker">Curated collections</div>
            <h2>Reading lists from the community.</h2>
          </div>
        </header>
        <div className="collections-grid">
          {COLLECTIONS.map((c, i) => (
            <article key={i} className="coll-card">
              <div className="coll-stack">
                <div className="coll-thumb" style={{ background: `linear-gradient(135deg, ${PEOPLE[i % PEOPLE.length].accent}, ${shade(PEOPLE[i % PEOPLE.length].accent, -30)})` }} />
                <div className="coll-thumb" style={{ background: "linear-gradient(135deg,#1B1B1B,#3A3A3A)" }} />
                <div className="coll-thumb" style={{ background: "linear-gradient(135deg,#E6D8C9,#9C8A6E)" }} />
              </div>
              <div className="coll-meta">
                <div className="coll-title">{c.title}</div>
                <div className="coll-count mono">{c.count} items · by @{c.curator}</div>
              </div>
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Landing, Profile, ProjectPage, Explore, LogoMark });
