function Experience() {
  const [entries, setEntries] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    fetch("experience.json", { cache: "no-cache" })
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((data) => setEntries(Array.isArray(data) ? data : [data]))
      .catch((e) => {
        console.error("Failed to load experience.json", e);
        setError(e.message);
        setEntries([]);
      });
  }, []);

  return (
    <section id="experience" data-screen-label="Experience">
      <div className="reveal">
        <Eyebrow>03 · Experience</Eyebrow>
        <h2 className="section-title">A timeline of building.</h2>
      </div>
      <div className="exp reveal" data-delay="1">
        {entries === null && (
          <div className="exp-loading">Loading experience…</div>
        )}
        {error && (
          <div className="exp-loading" style={{ color: "var(--danger)" }}>
            Failed to load experience.json
          </div>
        )}
        {entries &&
          entries.map((entry, idx) => (
            <ExperienceCard key={idx} entry={entry} />
          ))}
      </div>
    </section>
  );
}

function ExperienceCard({ entry }) {
  const {
    role,
    company,
    period,
    tags = [],
    summary,
    highlights = [],
  } = entry;
  return (
    <div className="exp-entry">
      <div className="exp-node"></div>
      <article className="exp-card">
        <div className="exp-card-top">
          <div className="exp-role">
            {role} {company && <span className="at">@ {company}</span>}
          </div>
          {period && <span className="exp-time">{period}</span>}
        </div>
        {tags.length > 0 && (
          <div className="exp-sub">{tags.join(" · ")}</div>
        )}
        {summary && <p className="exp-body">{summary}</p>}
        {highlights.length > 0 && (
          <div className="exp-wins">
            {highlights.map((h, i) => (
              <div key={i} className="exp-win">
                <span className="marker">
                  {String(i + 1).padStart(2, "0")}
                </span>
                <span>{h}</span>
              </div>
            ))}
          </div>
        )}
      </article>
    </div>
  );
}

function TechStack() {
  const [data, setData] = React.useState(null);
  const [tab, setTab] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    fetch("stack.json", { cache: "no-cache" })
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((d) => {
        setData(d);
        if (d.categories && d.categories.length > 0) setTab(d.categories[0].id);
      })
      .catch((e) => {
        console.error("Failed to load stack.json", e);
        setError(e.message);
      });
  }, []);

  const categories = (data && data.categories) || [];
  const active = categories.find((c) => c.id === tab);

  return (
    <section id="stack" data-screen-label="Tech Stack">
      <div className="reveal">
        <Eyebrow>04 · Stack</Eyebrow>
        <h2 className="section-title">Tools, opinionated.</h2>
        <p className="section-lead">
          A working stack assembled around clarity, scale, and operational sanity
          — not novelty.
        </p>
      </div>
      {error && (
        <div className="exp-loading" style={{ color: "var(--danger)" }}>
          Failed to load stack.json
        </div>
      )}
      {!error && data === null && (
        <div className="exp-loading">Loading stack…</div>
      )}
      {categories.length > 0 && (
        <div className="stack-tabs reveal" data-delay="1">
          {categories.map((c) => (
            <button
              key={c.id}
              className={`stack-tab ${tab === c.id ? "active" : ""}`}
              onClick={() => setTab(c.id)}
            >
              {c.label}
            </button>
          ))}
        </div>
      )}
      {active && (
        <div className="stack-grid reveal" data-delay="2">
          {active.items.map((it) => (
            <div key={`${active.id}-${it.name}`} className="stack-cell">
              <span className="corner"></span>
              <span className="glyph">{it.glyph}</span>
              <span className="name">{it.name}</span>
              <span className="desc">{it.desc}</span>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}

function Projects() {
  const [items, setItems] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    fetch("projects.json", { cache: "no-cache" })
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((d) => setItems(Array.isArray(d) ? d : []))
      .catch((e) => {
        console.error("Failed to load projects.json", e);
        setError(e.message);
        setItems([]);
      });
  }, []);

  return (
    <section id="projects" data-screen-label="Projects">
      <div className="reveal">
        <Eyebrow>05 · Projects</Eyebrow>
        <h2 className="section-title">Selected work.</h2>
        <p className="section-lead">
          Systems shipped, AI experiments productionized, and platforms built
          for teams who actually use them.
        </p>
      </div>
      {error && (
        <div className="exp-loading" style={{ color: "var(--danger)" }}>
          Failed to load projects.json
        </div>
      )}
      {items === null && !error && (
        <div className="exp-loading">Loading projects…</div>
      )}
      {items && items.length > 0 && (
        <div className="proj-grid">
          {items.map((p, i) => (
            <article
              key={p.title || i}
              className="proj-card reveal"
              data-delay={(i % 2) + 1}
            >
              <div className={`proj-visual ${p.visual || ""}`}>
                <div className="proj-label">
                  <span>{p.label}</span>
                  {p.status && <span className="status">{p.status}</span>}
                </div>
                {p.code && <code>{p.code}</code>}
              </div>
              <div className="proj-body">
                <h3>{p.title}</h3>
                {p.description && <p>{p.description}</p>}
                {p.tech && p.tech.length > 0 && (
                  <div className="proj-tech">
                    {p.tech.map((t) => (
                      <span key={t} className="t">
                        {t}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </article>
          ))}
        </div>
      )}
    </section>
  );
}

Object.assign(window, { Experience, TechStack, Projects });
