const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS } = React;

function Hero({ profile, tweaks = {} }) {
  const phrases = [
    "I don't demo notebooks. I ship inference endpoints.",
    "Fine-tuned DeepSeek → prod at 10× lower cost than GPT-4.",
    "RAG + MCP + PKCE auth for 5,000+ SAP engineers.",
    "GCP · AWS · SAP BTP · LangGraph · FastAPI.",
  ];

  // Split headline around the accent phrase
  const full = tweaks.heroHeadline || "Software Developer, built on production data.";
  const accentPhrase = tweaks.heroAccentText || "built on production data.";
  let before = full, after = "";
  const idx = full.toLowerCase().indexOf(accentPhrase.toLowerCase());
  if (idx >= 0) {
    before = full.slice(0, idx);
    after = full.slice(idx + accentPhrase.length);
  }

  return (
    <header className="hero">
      <div className="hero-visual" aria-hidden="true" />
      <div className="hero-chibi" aria-hidden="true"><img src="assets/rohan-chibi.png" alt="" /></div>
      <div className="hero-content">
        <div className="hero-eyebrow">
          <StatusDot>Open to opportunities</StatusDot>
          <span className="dot-sep">·</span>
          <span>{profile.location}</span>
        </div>
        <h1>
          {before}
          {idx >= 0 && <span className="accent">{accentPhrase}</span>}
          {after}
        </h1>
        <p className="hero-role">
          <Typewriter phrases={phrases} />
        </p>
        <p className="hero-summary">{profile.summary}</p>
        <div className="hero-ctas">
          <a className="hero-cta primary" href="assets/rohan-waghmare-resume.pdf" download>Resume ↓</a>
          <a className="hero-cta secondary" href={`mailto:${profile.email}`}>Contact</a>
        </div>
      </div>
      <div className="hero-footer">
        <div className="hero-tag">
          Eliminating <b>slow GPT-4 pipelines</b> and replacing them with <span className="accent">fine-tuned, self-hosted</span> systems — at 10× lower cost — that ship to production.
        </div>
        <div className="hero-stats">
          <div className="hero-stat">
            <div className="val">100<sup>%</sup></div>
            <div className="lbl">Domain extraction accuracy</div>
          </div>
          <div className="hero-stat">
            <div className="val">30<sup>×</sup></div>
            <div className="lbl">Cost reduction vs GPT-4</div>
          </div>
          <div className="hero-stat">
            <div className="val">5K<sup>+</sup></div>
            <div className="lbl">Developers served monthly</div>
          </div>
        </div>
      </div>
    </header>
  );
}

function About({ education, skills }) {
  return (
    <section className="sec" id="about">
      <SectionHeader num="01" title="about" kicker="background & toolkit" />
      <div className="about-grid">
        <div className="about-card">
          <h3>education</h3>
          {education.map((e, i) => (
            <div className="edu-item" key={i}>
              <div className="edu-school">{e.school}</div>
              <div className="edu-degree">{e.degree}</div>
              <div className="edu-period">{e.period}</div>
              <div className="edu-courses">{e.courses}</div>
            </div>
          ))}
        </div>
        <div className="about-card">
          <h3>skills</h3>
          {skills.map((s, i) => (
            <div className="skill-group" key={i}>
              <div className="skill-group-label">{s.group.toLowerCase()}</div>
              <div className="skill-items">
                {s.items.map((t) => <Tag key={t}>{t}</Tag>)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Experience({ experience }) {
  return (
    <section className="sec" id="experience">
      <SectionHeader num="02" title="experience" kicker="where I've shipped" />
      <div className="xp-list">
        {experience.map((xp) => (
          <article className="xp-item" key={xp.id}>
            <div className="xp-period">
              <div className="start">{xp.start}</div>
              <div>→ {xp.end}</div>
              <div style={{ marginTop: 10, color: "var(--faint)", fontSize: 11 }}>{xp.location}</div>
            </div>
            <div>
              <h3 className="xp-role">{xp.role}</h3>
              <div className="xp-company">{xp.company}</div>
              <ul className="xp-bullets">
                {xp.bullets.map((b, i) => <li key={i}>{b}</li>)}
              </ul>
              <div className="xp-tags">
                {xp.tags.map((t) => <Tag key={t}>{t}</Tag>)}
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function Projects({ projects, onOpen }) {
  // Gather all tags
  const allTags = useMemoS(() => {
    const set = new Set();
    projects.forEach((p) => p.tags.forEach((t) => set.add(t)));
    return ["All", ...Array.from(set).sort()];
  }, [projects]);
  const [activeTag, setActiveTag] = useStateS("All");
  const [activeKind, setActiveKind] = useStateS("All");
  const allKinds = useMemoS(() => ["All", ...Array.from(new Set(projects.map((p) => p.kind)))], [projects]);

  const filtered = projects.filter((p) => {
    const tagOk = activeTag === "All" || p.tags.includes(activeTag);
    const kindOk = activeKind === "All" || p.kind === activeKind;
    return tagOk && kindOk;
  });

  return (
    <section className="sec" id="work">
      <SectionHeader num="03" title="selected work" kicker="click to expand a case study" />

      <div className="proj-filter">
        <span className="proj-filter-label">kind:</span>
        {allKinds.map((k) => (
          <Tag key={k} active={activeKind === k} onClick={() => setActiveKind(k)}>{k.toLowerCase()}</Tag>
        ))}
      </div>
      <div className="proj-filter">
        <span className="proj-filter-label">stack:</span>
        {allTags.map((t) => (
          <Tag key={t} active={activeTag === t} onClick={() => setActiveTag(t)}>{t.toLowerCase()}</Tag>
        ))}
        <span className="proj-count">{filtered.length} / {projects.length}</span>
      </div>

      <div className="proj-grid">
        {filtered.map((p, i) => (
          <div
            className="proj-row"
            key={p.id}
            onClick={() => onOpen(p.id)}
            onMouseMove={(e) => {
              const r = e.currentTarget.getBoundingClientRect();
              e.currentTarget.style.setProperty("--mx", (e.clientX - r.left) + "px");
            }}
          >
            <div className="proj-idx">{String(i + 1).padStart(2, "0")}</div>
            <div className="proj-main">
              <div className="proj-top">
                <span className="proj-title">{p.title}</span>
                <span className="proj-kind">· {p.kind}</span>
                <span className="proj-year">· {p.year}</span>
              </div>
              <div className="proj-blurb">{p.blurb}</div>
              <div className="proj-bottom">
                <div className="proj-metrics">
                  {p.metrics.map(([v, l], i) => (
                    <span className="proj-metric" key={i}><b>{v}</b> {l}</span>
                  ))}
                </div>
              </div>
            </div>
            <div className="proj-arrow">→</div>
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: 40, textAlign: "center", color: "var(--muted)", fontSize: 13, borderTop: "1px solid var(--rule)" }}>
            <Prompt cursor>no matches. reset filters.</Prompt>
          </div>
        )}
      </div>
    </section>
  );
}

function Footer({ profile, onEgg }) {
  return (
    <footer className="footer">
      <div className="footer-cta">
        <h2>Let's build something.</h2>
        <p>Open to AI/ML, backend, and platform roles — wherever the system is underbuilt and the stakes are real. Happy to chat agentic systems, fine-tuning, or cloud infra.</p>
        <StatusDot>Replying within 24hrs</StatusDot>
      </div>
      <div className="footer-links">
        <a href={`mailto:${profile.email}`}>
          <span>{profile.email}</span><span className="arr">→</span>
        </a>
        <a href={`https://linkedin.com${profile.linkedin}`} target="_blank" rel="noreferrer">
          <span>linkedin.com{profile.linkedin}</span><span className="arr">→</span>
        </a>
        <a href={`https://github.com${profile.github}`} target="_blank" rel="noreferrer">
          <span>github.com{profile.github}</span><span className="arr">→</span>
        </a>
        <a href="#" onClick={(e) => { e.preventDefault(); onEgg(); }}>
          <span>$ whoami</span><span className="arr">↵</span>
        </a>
      </div>
      <div className="colophon">
        <span>© {new Date().getFullYear()} {profile.name}. Built in one sitting.</span>
        <span>JetBrains Mono · React · no framework</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Hero, About, Experience, Projects, Footer });
