// Main app for Farseen Shaikh portfolio
const { useState, useEffect, useRef, useMemo } = React;

// ——— Shared primitives ———

function useInView(ref, opts = {}) {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current || seen) return;
    const io = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } },
      { threshold: 0.25, ...opts }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [ref, seen]);
  return seen;
}

function Counter({ to, suffix = "", duration = 1400, decimals }) {
  const ref = useRef(null);
  const seen = useInView(ref);
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!seen) return;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(to * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
      else setVal(to);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [seen, to, duration]);
  const d = decimals ?? (Number.isInteger(to) ? 0 : (to < 10 ? 2 : 1));
  return <span ref={ref}>{val.toFixed(d)}{suffix}</span>;
}

function Section({ id, label, title, kicker, children }) {
  return (
    <section id={id} className="section">
      <div className="section-head">
        <div className="section-label">{label}</div>
        <h2 className="section-title">{title}</h2>
        {kicker && <p className="section-kicker">{kicker}</p>}
      </div>
      {children}
    </section>
  );
}

// ——— Hero ———

function Hero() {
  return (
    <header className="hero-cv">
      <div className="hero-cv-main">
        <div className="hero-cv-header">
          <div className="hero-cv-label mono">PORTFOLIO · UPDATED APR 2026</div>
          <h1 className="hero-cv-name">Farseen Shaikh</h1>
          <p className="hero-cv-role">
            I work on how information is <em>represented</em> to and within neural networks &mdash; and how that determines performance more than scale.
          </p>
          <p className="hero-cv-location mono">Independent AI Researcher · India · Open to remote &amp; relocation</p>
        </div>

        <div className="hero-cv-about">
          <p>
            I work at the intersection of <strong>interpretability</strong>, <strong>retrieval</strong>, and <strong>LLM agents</strong>.
            My thesis across four sole-author papers in 2026:
            how information is represented to and within neural networks matters more than
            scale or compute. I invented <strong>SAE-LoRA</strong> — a technique for adapting frozen sparse-autoencoder
            features to downstream tasks — and applied it to smart-contract auditing with a <strong>37.6×</strong> lift
            over frozen baselines.
          </p>
          <p>
            No lab. No advisor. No co-authors. I also ship: PaperMind AI runs in production on AWS Bedrock,
            and GOATsolana-MCP was the first MCP server connecting Claude to Solana.
          </p>
        </div>

        <nav className="hero-cv-links">
          <a href="mailto:farseenshaikh20@gmail.com" className="hero-link">Email</a>
          <a href="https://github.com/FarseenSh" target="_blank" rel="noreferrer" className="hero-link">GitHub</a>
          <a href="https://huggingface.co/Farseen0" target="_blank" rel="noreferrer" className="hero-link">HuggingFace</a>
          <a href="https://openreview.net/profile?id=~Farseen_Shaikh1" target="_blank" rel="noreferrer" className="hero-link">OpenReview</a>
          <a href="assets/Farseen_Shaikh_CV.pdf" download className="hero-link">CV (PDF)</a>
        </nav>
      </div>
    </header>
  );
}

// ——— Recent activity (quiet footer log) ———

function RecentActivity() {
  const news = [
    { date: "Mar 2026", text: "SCAR — sparse retrieval for smart-contract auditing — completed and posted to arXiv." },
    { date: "Feb 2026", text: "SweeperLLM — agentic self-correction for code generation — posted to arXiv." },
    { date: "Jan 2026", text: "Appointed team captain for Cohere Labs' Expedition Tiny Aya." },
    { date: "Dec 2025", text: "JumpReLU SAE training run on Qwen2.5 7B completed — first interpretability artifact released." }
  ];
  return (
    <div className="activity-log">
      {news.map((n, i) => (
        <div key={i} className="activity-row">
          <span className="activity-date mono">{n.date}</span>
          <span className="activity-text">{n.text}</span>
        </div>
      ))}
    </div>
  );
}

// ——— Stat bar ———

function StatBar() {
  return (
    <div className="stat-bar">
      {window.STATS.map((s, i) => (
        <div key={i} className="stat">
          <div className="stat-value">
            <Counter to={s.value} suffix={s.suffix} />
          </div>
          <div className="stat-label">{s.label}</div>
          <div className="stat-sub">{s.sub}</div>
        </div>
      ))}
    </div>
  );
}

// ——— Research papers ———

function Tag({ children, active, onClick }) {
  return (
    <button
      className={`tag ${active ? "active" : ""}`}
      onClick={onClick}
      type="button"
    >
      {children}
    </button>
  );
}

function PaperCard({ paper, index, expanded, onToggle, highlight }) {
  return (
    <article className={`paper ${expanded ? "expanded" : ""}`}>
      <button className="paper-head" onClick={onToggle} aria-expanded={expanded}>
        <div className="paper-index mono">P.{String(index + 1).padStart(2, "0")}</div>
        <div className="paper-content">
          <div className="paper-meta">
            <span className="mono">{paper.venueShort}</span>
            <span className="dot" />
            <span className="mono subtle">{paper.role}</span>
          </div>
          <h3 className="paper-title">{highlight ? <Highlight text={paper.title} q={highlight} /> : paper.title}</h3>
          <p className="paper-tldr">{highlight ? <Highlight text={paper.tldr} q={highlight} /> : paper.tldr}</p>
          <div className="paper-tags">
            {paper.tags.map(t => <span key={t} className="chip">{t}</span>)}
            <span className="paper-toggle mono">{expanded ? "− collapse" : "+ read more"}</span>
          </div>
        </div>
      </button>
      {expanded && (
        <div className="paper-body">
          <div className="paper-headline">
            <span className="mono subtle small">HEADLINE</span>
            <p>{paper.headline}</p>
          </div>
          <div className="paper-grid">
            <div>
              <h4>The problem</h4>
              <p>{paper.problem}</p>
              <h4>The method</h4>
              <ul>
                {paper.method.map((m, i) => <li key={i}>{m}</li>)}
              </ul>
              <h4>Why it matters</h4>
              <p>{paper.matters}</p>
            </div>
            <aside className="paper-results">
              <div className="mono subtle small">KEY RESULTS</div>
              {paper.results.map(([k, v], i) => (
                <div key={i} className="result-row">
                  <div className="result-k">{k}</div>
                  <div className="result-v mono">{v}</div>
                </div>
              ))}
              {paper.links.length > 0 && (
                <div className="paper-links">
                  {paper.links.map(l => (
                    <a key={l.href} href={l.href} target="_blank" rel="noreferrer">{l.label} ↗</a>
                  ))}
                </div>
              )}
            </aside>
          </div>
        </div>
      )}
    </article>
  );
}

function Highlight({ text, q }) {
  if (!q) return text;
  const re = new RegExp(`(${q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "gi");
  const parts = text.split(re);
  return parts.map((p, i) => re.test(p)
    ? <mark key={i}>{p}</mark>
    : <span key={i}>{p}</span>
  );
}

function ResearchProjects() {
  const [q, setQ] = useState("");
  const [activeTag, setActiveTag] = useState(null);
  const [openId, setOpenId] = useState(null);

  const allTags = useMemo(() => {
    const s = new Set();
    window.PAPERS.forEach(p => p.tags.forEach(t => s.add(t)));
    window.PROJECTS.forEach(p => p.tags.forEach(t => s.add(t)));
    return Array.from(s);
  }, []);

  const match = (item) => {
    if (activeTag && !item.tags.includes(activeTag)) return false;
    if (!q) return true;
    const ql = q.toLowerCase();
    const hay = [item.title || item.name, item.tldr, item.headline, item.kicker, ...(item.tags || [])]
      .filter(Boolean).join(" ").toLowerCase();
    return hay.includes(ql);
  };

  const papers = window.PAPERS.filter(match);
  const projects = window.PROJECTS.filter(match);

  return (
    <>
      <Section id="research" label="§ 01 / Research" title="Four papers. All sole-author." kicker="Click any paper to expand method, results, and why it matters.">
        <div className="filter-bar">
          <div className="search-wrap">
            <span className="mono subtle small">SEARCH</span>
            <input
              value={q}
              onChange={e => setQ(e.target.value)}
              placeholder="Try: SAE, RAG, Solana, self-correction…"
              className="search-input"
            />
            {q && <button className="clear-btn" onClick={() => setQ("")}>×</button>}
          </div>
          <div className="tag-row">
            <Tag active={!activeTag} onClick={() => setActiveTag(null)}>All</Tag>
            {allTags.map(t => (
              <Tag key={t} active={activeTag === t} onClick={() => setActiveTag(activeTag === t ? null : t)}>{t}</Tag>
            ))}
          </div>
        </div>
        <div className="papers">
          {papers.length === 0 && <div className="empty mono">No papers match “{q}”.</div>}
          {papers.map((p, i) => (
            <PaperCard
              key={p.id}
              paper={p}
              index={i}
              expanded={openId === p.id}
              onToggle={() => setOpenId(openId === p.id ? null : p.id)}
              highlight={q}
            />
          ))}
        </div>
      </Section>

      <Section id="projects" label="§ 02 / Projects" title="Shipped things." kicker="Research only matters when it ships. These do.">
        <div className="projects">
          {projects.length === 0 && <div className="empty mono">No projects match “{q}”.</div>}
          {projects.map(p => <ProjectCard key={p.id} project={p} highlight={q} />)}
        </div>
      </Section>
    </>
  );
}

function ProjectCard({ project, highlight }) {
  return (
    <article className="project">
      <div className="project-head">
        <div className="project-meta">
          <span className="mono">{project.year}</span>
          <span className="dot" />
          <span className="mono subtle">{project.kicker}</span>
        </div>
        <h3 className="project-name">{highlight ? <Highlight text={project.name} q={highlight} /> : project.name}</h3>
      </div>
      <p className="project-tldr">{highlight ? <Highlight text={project.tldr} q={highlight} /> : project.tldr}</p>
      <div className="project-highlight mono small">{project.highlight}</div>
      <div className="project-stack mono subtle small">{project.stack}</div>
      <div className="project-bottom">
        <div className="project-tags">
          {project.tags.map(t => <span key={t} className="chip">{t}</span>)}
        </div>
        <div className="project-links">
          {project.links.map(l => (
            <a key={l.href} href={l.href} target="_blank" rel="noreferrer" className="mono">{l.label} ↗</a>
          ))}
        </div>
      </div>
    </article>
  );
}

Object.assign(window, {
  Hero, StatBar, ResearchProjects, Section, Counter, RecentActivity
});
