/* Pages, Home + CaseStudy views */

const { useEffect, useState } = React;

/* =====================================================
   HOME
   ===================================================== */
function Home({ goCase }) {
  const { PROFILE, WORK, APPROACH, EXPERIENCE, HONORS, PHILOSOPHY } = window.PORTFOLIO_DATA;
  const [experienceExpanded, setExperienceExpanded] = useState(false);
  const visibleExperience = experienceExpanded ? EXPERIENCE : EXPERIENCE.slice(0, 5);

  return (
    <main>
      {/* ----- HERO ----- */}
      {window.__HERO_VARIANT === "v2" ? <HeroV2 /> : (
      <section className="hero" id="top">
        <div className="wrap">
          <div className="hero-eyebrow">
            <span className="mono">Available For On-site, Remote, or hybrid</span>
          </div>

          <h1 className="t-display hero-statement">
            {PROFILE.name}.<br />
            {PROFILE.title}.<br />
            <span className="accent">
              I make products<br />
              feel{" "}
              <span className="obvious-key">
                {"obvious".split("").map((ch, i) => (
                  <span key={i} style={{ "--n": i }}>{ch}</span>
                ))}
              </span>{" "}
              for<br />
              technology that isn’t.
            </span>
          </h1>

          <HeroSlider />

          <div className="hero-meta-grid">
            <div className="hero-meta">
              <span className="k">Based</span>
              <div className="v">{PROFILE.location}</div>
            </div>
            <div className="hero-meta hero-meta--grow">
              <span className="k">Now</span>
              <div className="v">Freelance · Tallinn · Remote · Clients in the US/CA/EU</div>
            </div>
            <div className="hero-meta">
              <span className="k">Email</span>
              <div className="v">
                <a href={`mailto:${PROFILE.email}`}>{PROFILE.email}</a>
              </div>
            </div>
            <div className="hero-meta">
              <span className="k">Elsewhere</span>
              <div className="v">
                <a href={`https://${PROFILE.linkedin}`} target="_blank" rel="noopener">LinkedIn ↗</a>
              </div>
            </div>
          </div>
        </div>
      </section>
      )}

      {/* ----- WORK ----- */}
      <section className="section" id="work">
        <div className="wrap">
          <SectionHeader
            num="01"
            label="Selected Work"
            title="Four selected<br />projects."
            aside="Each project led end-to-end. Read the long-form case study for context, role, decisions, tradeoffs, and what changed after launch." />
          

          <div className="work-list">
            {WORK.map((p) =>
            <FadeIn key={p.slug}>
                <article className="work-row">
                  <div className="col-head">
                    <h3 className="work-title">{p.title}</h3>
                    <div className="work-domain">{p.domain}</div>
                  </div>
                  <div className="col-summary">{p.summary}</div>
                  <div className="col-meta">
                    <div className="meta-row"><span className="k">Year</span><span className="v">{p.year}</span></div>
                    <div className="meta-row"><span className="k">Role</span><span className="v">{p.role}</span></div>
                  </div>
                  <div className="col-cta">
                    <CTAButton onClick={() => goCase(p.slug)}>Read case study</CTAButton>
                  </div>
                </article>
              </FadeIn>
            )}
          </div>
        </div>
      </section>

      {/* ----- ABOUT ----- */}
      <section className="section" id="about">
        <div className="wrap">
          <SectionHeader
            num="02"
            label="About"
            title="Senior designer,<br />co-founder, systems lead."
            aside="Fourteen years across fintech, mobility and AI. Based in Tallinn, working globally." />
          

          <div className="about-grid">
            <div className="about-aside">
              <img className="about-photo" src="/assets/profile.png" alt={PROFILE.name} loading="lazy" />
            </div>
            <div className="about-body">
              <p>
                I've spent <strong>{PROFILE.years} years</strong> designing software in places where the stakes were real, a ride-hailing app moving five million rides a day, a back-office where a quarter-million livelihoods sit, an AI coach that had to feel safe even when the model was wrong.
              </p>
              <p>
                I work end-to-end: research, strategy, systems, interaction, motion, and design QA in the build. I'm equally comfortable owning the file alone or running a team of designers, and I lean into engineering, tokens, theming, performance, because the parts of design that scale live there.
              </p>
              <p>
                Off the file I read Dieter Rams more than I should, collect old industrial catalogues, and run a small weekly review practice that has saved me more than any tool.
              </p>

              <div className="about-interests">
                <div className="k">Interests</div>
                <div className="v">
                  <span>Travel</span>
                  <span>Music</span>
                  <span>Football</span>
                  <span>AI</span>
                  <span>Movies</span>
                  <span>Everyday learning</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ----- RESUME / CV ----- */}
      <section className="section" id="resume">
        <div className="wrap">
          <SectionHeader
            num="03"
            label="Résumé"
            title="The résumé."
            aside="One page, every role, with measured outcomes alongside each line. Take the PDF for sharing or for a tracking system." />


          <div className="resume-block">
            <div className="body">
              <p className="t-lede" style={{ color: "var(--fg)" }}>
                A condensed one-page CV: every role, every shipped product, with measured outcomes alongside each line.
              </p>
              <div className="links">
                <CTAButton href="/assets/Mazdak-Shakiba-Resume.pdf" variant="solid" target="_blank" rel="noopener">Download PDF</CTAButton>
                <CTAButton href={`https://${PROFILE.linkedin}`} variant="subtle" target="_blank" rel="noopener">View on LinkedIn</CTAButton>
              </div>
            </div>
            <div className="label">
Updated September 2026<br />
              PDF · 1 page · ~36 KB
            </div>
          </div>
        </div>
      </section>

      {/* ----- EXPERIENCE ----- */}
      <section className="section" id="experience">
        <div className="wrap">
          <SectionHeader
            num="04"
            label="Experience"
            title="Roles,<br />recent first."
            aside="Five most recent below. Expand for the deeper bench, or take it to LinkedIn." />


          <div className="tl">
            {visibleExperience.map((e, i) =>
            <div className="tl-row" key={i}>
                <div className="y">{e.y}</div>
                <div className="co">{e.co}</div>
                <div className="ro">{e.ro}</div>
                <div className="loc">{e.loc}</div>
              </div>
            )}
          </div>

          {EXPERIENCE.length > 5 ? (
            <div className="tl-actions">
              <CTAButton onClick={() => setExperienceExpanded(!experienceExpanded)} variant="subtle">
                {experienceExpanded ? "Show less" : `Read more (+${EXPERIENCE.length - 5})`}
              </CTAButton>
              <CTAButton href={`https://${PROFILE.linkedin}`} variant="subtle" target="_blank" rel="noopener">
                Explore more on LinkedIn
              </CTAButton>
            </div>
          ) : null}
        </div>
      </section>

      {/* ----- HONORS & AWARDS ----- */}
      <section className="section" id="honors">
        <div className="wrap">
          <SectionHeader
            num="05"
            label="Honors & Awards"
            title="Outside<br />recognition."
            aside="A short list, kept honest. Industrial design first, then startup work that the room outside Estonia noticed." />

          <div className="honors-list">
            {HONORS.map((h, i) => (
              <div className="honor-row" key={i}>
                <div className="y">{h.year}</div>
                <div className="t">{h.title}</div>
                <div className="c">{h.co}</div>
                <div className="o">{h.loc}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ----- PHILOSOPHY ----- */}
      <section className="philosophy" id="philosophy">
        <div className="wrap">
          <div className="philosophy-eyebrow">
            <span>Design philosophy</span>
          </div>

          <h2 className="philosophy-statement">
            Clarity over cleverness.<br />
            <span className="muted-2">Strict grid, two typefaces, no ornament. Meaning is structural.</span>
          </h2>

          <div className="philosophy-tenets">
            {PHILOSOPHY.tenets.map((t) =>
            <div className="tenet" key={t.n}>
                <div className="h">{t.h}</div>
                <div className="p">{t.p}</div>
              </div>
            )}
          </div>
        </div>
      </section>

      <Footer />
    </main>);

}

/* =====================================================
   CASE STUDY, editorial layout w/ sticky TOC
   (Smart Coach standalone structure, portfolio design language)
   ===================================================== */
function CaseStudy({ slug, goHome, goCase }) {
  const { WORK, PROFILE } = window.PORTFOLIO_DATA;
  const project = WORK.find((p) => p.slug === slug);
  const narrative = window.NARRATIVES[slug];

  useEffect(() => { window.scrollTo({ top: 0, behavior: "auto" }); }, [slug]);

  // TOC active highlight via IntersectionObserver
  useEffect(() => {
    if (!project) return;
    const sections = document.querySelectorAll("section.cs-block, .cs-foot");
    const tocLinks = document.querySelectorAll(".cs-toc a");
    const linkBySectionId = new Map();
    tocLinks.forEach((a) => {
      const id = a.getAttribute("href").replace(/^#/, "");
      linkBySectionId.set(id, a);
    });
    const setActive = (id) => {
      tocLinks.forEach((a) => {
        a.classList.remove("active");
        a.parentElement.classList.remove("active");
      });
      const a = linkBySectionId.get(id);
      if (a) {
        a.classList.add("active");
        a.parentElement.classList.add("active");
      }
    };
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
      },
      { rootMargin: "-30% 0px -60% 0px", threshold: 0 }
    );
    sections.forEach((s) => { if (s.id) io.observe(s); });
    return () => io.disconnect();
  }, [slug]);

  if (!project || !narrative) return null;

  const nextIdx = (WORK.findIndex((p) => p.slug === slug) + 1) % WORK.length;
  const next = WORK[nextIdx];

  // Eyebrow label badges derived from project metadata
  const domainParts = project.domain.split("·").map((s) => s.trim());
  const eyebrowLabs = [
    { text: project.year, live: false },
    ...domainParts.map((d) => ({ text: d, live: false })),
  ];

  const heroMeta = [
    { k: "Role", v: project.role },
    { k: "Team", v: project.team },
    { k: "Timeline", v: project.timeline },
  ];

  return (
    <main className="cs-main">
      <div className="cs-layout">
        {/* ---------- Main content column ---------- */}
        <article className="cs-content">

          {/* ---------- Cover ---------- */}
          <figure className="cs-cover">
            <img src={project.cover} alt={`${project.title}, cover`} loading="eager" />
          </figure>

          {/* ---------- Hero ---------- */}
          <header className="cs-hero-block">
            <div className="cs-eyebrow">
              <span className="cs-back" onClick={goHome}>← Back to index</span>
              <span className="lab">Case study</span>
              {eyebrowLabs.map((l, i) => (
                <span key={i} className="lab">{l.text}</span>
              ))}
            </div>

            <h1 className="cs-title">{project.title}</h1>

            <p className="cs-deck cs-deck-lead">{project.headline}</p>

            <p className="cs-deck">{project.summary}</p>

            <div className="cs-meta">
              {heroMeta.map((m, i) => (
                <div className="cell" key={i}>
                  <div className="k">{m.k}</div>
                  <div className="v">{m.v}</div>
                </div>
              ))}
            </div>
          </header>

          {/* ---------- 01 Outcome ---------- */}
          <section className="cs-block" id="outcome">
            <div className="cs-section-label">
              <span>Outcome</span>
            </div>
            <h2 className="cs-h2">What shipped, and what it changed.</h2>
            <div className="cs-prose">
              <p>Measured outcomes from launch, the metrics we instrumented with engineering before ship, and read the week after.</p>
            </div>
            <div className="cs-outcome-grid">
              {project.stats.map((s, i) => (
                <div className="cs-outcome" key={i}>
                  <div className="num">
                    <span>{s.num}</span>
                    {s.unit ? <span className="unit">{s.unit}</span> : null}
                  </div>
                  <div className="label">{s.label}</div>
                </div>
              ))}
            </div>
          </section>

          {/* ---------- 02 Context ---------- */}
          <section className="cs-block" id="context">
            <div className="cs-section-label">
              <span>Context</span>
            </div>
            <h2 className="cs-h2">{project.title}, what made it interesting.</h2>
            <div className="cs-prose">
              <p dangerouslySetInnerHTML={{ __html: narrative.context }} />
            </div>
          </section>

          {/* ---------- 03 Role ---------- */}
          <section className="cs-block" id="role">
            <div className="cs-section-label">
              <span>My role</span>
            </div>
            <h2 className="cs-h2">What I owned, what the team did.</h2>
            <div className="cs-prose">
              <p>Explicit, because senior portfolios should be. The split between what I owned and what other contributors shipped is below.</p>
            </div>

            <div className="cs-role-split">
              <div>
                <div className="k">What I owned</div>
                <ul>{narrative.role.owned.map((x, i) => <li key={i}>{x}</li>)}</ul>
              </div>
              <div>
                <div className="k">Team contribution</div>
                <ul>{narrative.role.team.map((x, i) => <li key={i}>{x}</li>)}</ul>
              </div>
            </div>
          </section>

          {/* ---------- 04 Features ---------- */}
          <section className="cs-block" id="features">
            <div className="cs-section-label">
              <span>Features</span>
            </div>
            <h2 className="cs-h2">Three problems, three design moves.</h2>
            <div className="cs-prose">
              <p>Each block is framed the same way: the problem in the user's words, the design move, and the measured impact afterwards.</p>
            </div>

            {narrative.features.map((f, i) => {
              const img = project.images[i + 1] || project.images[0];
              return (
                <FadeIn key={i}>
                  <div className="cs-feature">
                    <div className="cs-feature-num">Feature</div>
                    <h3 className="cs-feature-title" dangerouslySetInnerHTML={{ __html: f.title }} />
                    <div className="cs-feature-grid">
                      <div className="cs-feature-block">
                        <div className="k">Challenge</div>
                        <p>{f.challenge}</p>
                      </div>
                      <div className="cs-feature-block">
                        <div className="k">Solution</div>
                        <p>{f.solution}</p>
                      </div>
                      <div className="cs-feature-block">
                        <div className="k">Impact</div>
                        <p>{f.impact}</p>
                      </div>
                    </div>
                    <figure className="cs-frame">
                      <img src={img} alt={f.title.replace(/<\/?em>/g, "")} loading="lazy" />
                      <figcaption className="cs-frame-cap">
                        <span className="num">Fig. 0{i + 2}</span>
                        <span>{f.title.replace(/<\/?em>/g, "")}</span>
                      </figcaption>
                    </figure>
                  </div>
                </FadeIn>
              );
            })}

            <blockquote className="cs-pull">
              <span dangerouslySetInnerHTML={{ __html: narrative.pull }} />
              <cite>, Reflection, project retrospective</cite>
            </blockquote>
          </section>

          {/* ---------- 05 Tradeoffs ---------- */}
          <section className="cs-block" id="tradeoffs">
            <div className="cs-section-label">
              <span>Decisions &amp; tradeoffs</span>
            </div>
            <h2 className="cs-h2">The calls that shaped everything after.</h2>

            <div className="cs-tradeoff">
              <div className="chose">
                <div className="k">We chose</div>
                <p>{narrative.tradeoff.chose}</p>
              </div>
              <div className="cut">
                <div className="k">We cut</div>
                <p>{narrative.tradeoff.cut}</p>
              </div>
            </div>
          </section>

          {/* ---------- 06 Reflection ---------- */}
          <section className="cs-block" id="reflection">
            <div className="cs-section-label">
              <span>Reflection</span>
            </div>
            <h2 className="cs-h2">What I'd do again, and what I'd do differently.</h2>
            <div className="cs-prose">
              <p>{narrative.reflection}</p>
            </div>

            {project.images.length > 3 ? (
              <div className="cs-gallery-2" style={{ marginTop: 48 }}>
                {project.images.slice(-Math.min(2, project.images.length)).map((src, i) => (
                  <figure className="cs-frame" key={i}>
                    <img src={src} alt="Production surface" loading="lazy" />
                    <figcaption className="cs-frame-cap">
                      <span className="num">Fig. {String(10 + i).padStart(2, "0")}</span>
                      <span>Production surface</span>
                    </figcaption>
                  </figure>
                ))}
              </div>
            ) : null}
          </section>

          {/* ---------- Next ---------- */}
          <div className="cs-foot" id="next">
            <div className="lab">Next case study</div>
            <div className="row" onClick={() => goCase(next.slug)}>
              <div>
                <div className="mono" style={{ marginBottom: 6 }}>{next.year} · {next.domain}</div>
                <div className="t">{next.title}</div>
              </div>
              <div className="arrow">→</div>
            </div>
          </div>

        </article>

        {/* ---------- Sticky right TOC ---------- */}
        <aside className="cs-toc" aria-label="Table of contents">
          <div className="cs-toc-head">On this page</div>
          <ul className="cs-toc-list">
            <li><a href="#outcome">Outcome</a></li>
            <li><a href="#context">Context</a></li>
            <li><a href="#role">My role</a></li>
            <li><a href="#features">Features</a></li>
            <li><a href="#tradeoffs">Tradeoffs</a></li>
            <li><a href="#reflection">Reflection</a></li>
            <li><a href="#next">Next</a></li>
          </ul>
        </aside>
      </div>

      <Footer />
    </main>
  );
}

/* =====================================================
   ASK AI, per-case-study question box
   ===================================================== */
function AskAI({ project, narrative, profile }) {
  const [q, setQ] = useState("");
  const [answer, setAnswer] = useState("");
  const [loading, setLoading] = useState(false);

  const buildContext = () => {
    const stats = project.stats.map((s) => `- ${s.num}${s.unit ? " " + s.unit : ""}: ${s.label}`).join("\n");
    const features = narrative.features
      .map((f, i) => `Feature ${i + 1}: ${f.title.replace(/<\/?em>/g, "")}\n  Challenge: ${f.challenge}\n  Solution: ${f.solution}\n  Impact: ${f.impact}`)
      .join("\n\n");
    return `You are answering questions about the ${project.title} case study by ${profile.name} (${project.year}).

Context: ${narrative.context.replace(/<[^>]+>/g, "")}

Role (owned): ${narrative.role.owned.join("; ")}
Team contribution: ${narrative.role.team.join("; ")}

Outcomes:
${stats}

${features}

Tradeoff, chose: ${narrative.tradeoff.chose}
Tradeoff, cut: ${narrative.tradeoff.cut}

Reflection: ${narrative.reflection}

Answer in 2–4 short sentences. If the question isn't covered, say so plainly and suggest emailing ${profile.name} at ${profile.email}.`;
  };

  const ask = async (question) => {
    if (!question) return;
    setLoading(true);
    setAnswer("Thinking…");
    try {
      const reply = await window.claude.complete({
        messages: [{ role: "user", content: buildContext() + "\n\nQuestion: " + question }],
      });
      setAnswer(reply.trim());
    } catch (err) {
      setAnswer(`Couldn't reach the AI just now. You can email ${profile.name} at ${profile.email}.`);
    }
    setLoading(false);
  };

  const chips = [
    "How did you measure impact?",
    "What did you cut and why?",
    "What would you carry into your next project?",
  ];

  return (
    <section className="cs-ask">
      <div className="lab">Ask AI about this case study</div>
      <h3>Curious about a specific decision?</h3>
      <p>Ask in plain English, answers pulled from the writeup above.</p>

      <div className="input">
        <input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") ask(q.trim()); }}
          placeholder={`e.g. ${chips[0]}`}
        />
        <button onClick={() => ask(q.trim())} disabled={loading}>Ask</button>
      </div>

      <div className="chips">
        {chips.map((c, i) => (
          <span className="chip" key={i} onClick={() => { setQ(c); ask(c); }}>{c}</span>
        ))}
      </div>

      {answer ? <div className="answer">{answer}</div> : null}
    </section>
  );
}

/* =====================================================
   FOOTER
   ===================================================== */
function Footer() {
  const { PROFILE } = window.PORTFOLIO_DATA;
  return (
    <footer className="contact" id="contact">
      <div className="wrap">
        <div className="contact-eyebrow">
          <span>Contact</span>
        </div>

        <h2>
          Designing<br />
          <span className="muted-2">something hard?</span><br />
          Let's talk.
        </h2>

        <p className="contact-lede">
          Senior or staff roles, remote or EU hybrid, open to relocation. Based in {PROFILE.location}, working globally. Replies in a day or two.
        </p>

        <div className="email-line">
          <a href={`mailto:${PROFILE.email}`}>{PROFILE.email}</a>
        </div>

        <div className="contact-channels">
          <a className="channel" href={`https://${PROFILE.linkedin}`} target="_blank" rel="noopener">LinkedIn ↗</a>
          <a className="channel" href={`tel:${PROFILE.phone.replace(/\s+/g, "")}`}>{PROFILE.phone}</a>
        </div>

        <div className="contact-foot">
          <div>© {PROFILE.name} · {new Date().getFullYear()}</div>
          <div>Designed and built by hand, no templates</div>
        </div>
      </div>
    </footer>);

}

Object.assign(window, { Home, CaseStudy, Footer });