/* Sections part 2: Work, CaseStudy (sticky scrollytelling), Process */
const { motion, useScroll: useScroll2, useTransform: useTransform2 } = window.Motion;
const { useRef: useRef2 } = React;

function Work() {
  const { projects } = window.PORTFOLIO_DATA;
  // Featured Work only shows projects that have a case-study banner.
  const featured = projects.filter((p) => p.img);
  return (
    <section id="work" className="sw">
      <div className="sw-head">
        <div className="eyebrow eyebrow-rust">Selected work</div>
        <h2 className="sw-title">Featured<br/><span className="outline-text">work.</span></h2>
        <p className="sw-sub">Three case studies — scroll to see each one stack on top of the last.</p>
      </div>
      <div className="sw-stack">
        {featured.map((p, i) => (<StackCard key={p.slug} project={p} i={i} total={featured.length} />))}
      </div>
      <div className="sw-tail" />
    </section>
  );
}

function StackCard({ project, i, total }) {
  const external = project.href && project.href.startsWith("http");
  const top = 70 + i * 28;
  const cardStyle = {
    top: `${top}px`,
    zIndex: 10 + i,
    backgroundImage: project.img ? `url("${project.img}")` : undefined,
  };
  return (
    <article
      className={`sw-card sw-card-${project.color} ${project.img ? "sw-card--bg" : ""}`}
      style={cardStyle}
    >
      <div className="sw-card-strip">
        <span className="sw-card-strip-l">
          <span className="sw-card-idx">0{i+1} / 0{total}</span>
          <span className="sw-card-tag">{project.year} · {project.role}</span>
        </span>
        <span className="sw-card-strip-r">{project.name}</span>
      </div>
      <div className="sw-card-body">
        <div className="sw-card-text">
          <h3 className="sw-card-name">{project.name}</h3>
          <p className="sw-card-desc">{project.body}</p>
          {project.href && project.href !== "#" ? (
            <a href={project.href} target={external ? "_blank" : undefined} rel={external ? "noopener noreferrer" : undefined} data-hover className="sw-card-cta">
              View case study <span className="sw-cta-arrow">↗</span>
            </a>
          ) : (
            <a href="#contact" data-hover className="sw-card-cta">
              Read founder story <span className="sw-cta-arrow">→</span>
            </a>
          )}
        </div>
      </div>
    </article>
  );
}

function CaseStudy() {
  const { caseStudy } = window.PORTFOLIO_DATA;
  const ref = useRef2(null);
  const { scrollYProgress } = useScroll2({ target: ref, offset: ["start start", "end end"] });
  const steps = caseStudy.steps;
  // Horizontal translate: pan across N panels. Total travel = (N-1) * 100vw
  const x = useTransform2(scrollYProgress, [0, 1], ["0%", `-${(steps.length - 1) * 100}%`]);

  return (
    <section id="case-studies" ref={ref} className="hs" style={{ height: `${steps.length * 100}vh` }}>
      <div className="hs-sticky">
        <div className="hs-eyebrow"><span className="line"/>Featured case studies<span className="line"/></div>
        <ScrollIndicator scrollYProgress={scrollYProgress} total={steps.length} />
        <motion.div className="hs-track" style={{ x }}>
          {steps.map((s, i) => (<CSPanel key={s.n} step={s} i={i} total={steps.length} progress={scrollYProgress} />))}
        </motion.div>
      </div>
    </section>
  );
}

function CSPanel({ step, i, total, progress }) {
  // Each panel's "active" range within scrollYProgress
  const panelStart = i / total;
  const panelEnd = (i + 1) / total;
  const local = useTransform2(progress, [panelStart, panelEnd], [0, 1]);
  const headlineY = useTransform2(local, [0, 1], [40, -40]);
  const opacity = useTransform2(progress, [Math.max(0, panelStart - 0.05), panelStart + 0.02, panelEnd - 0.02, Math.min(1, panelEnd + 0.05)], [0.3, 1, 1, 0.3]);
  const external = step.href && step.href.startsWith("http");

  return (
    <motion.article style={{ opacity }} className={`hs-panel hs-panel-${step.color}`}>
      <div className="hs-panel-inner">
        {/* Left text column */}
        <div className="hs-panel-left">
          <div className="hs-panel-meta">
            <span className="hs-panel-n">{step.n}</span>
            <span className="hs-panel-tag">{step.tag}</span>
            <span className="hs-panel-count">0{i+1} / 0{total}</span>
          </div>
          <motion.h3 style={{ y: headlineY }} className="hs-panel-title">{step.title}</motion.h3>

          <div className="hs-panel-sub">Problem</div>
          <p className="hs-panel-prob">{step.problem}</p>

          <div className="hs-panel-sub">Move</div>
          <p className="hs-panel-body">{step.body}</p>

          <div className="hs-panel-outcomes">
            {step.outcomes.map((o, oi) => (
              <span key={oi} className="hs-pill">{o}</span>
            ))}
          </div>

          {step.href && step.href !== "#" && (
            <a href={step.href} target={external ? "_blank" : undefined} rel={external ? "noopener noreferrer" : undefined} data-hover className="hs-panel-link">
              Read full case study ↗
            </a>
          )}
        </div>

        {/* Right banner */}
        <div className="hs-panel-right">
          {step.img ? (
            <div className="hs-banner-wrap">
              <img src={step.img} alt={`${step.title} banner`} className="hs-banner-img" />
            </div>
          ) : (
            <div className="hs-banner-wrap hs-banner-placeholder">
              <div className="hs-banner-mark">{step.title.split(" ")[0]}</div>
              <div className="hs-banner-sub">— founder case study</div>
            </div>
          )}
        </div>
      </div>
    </motion.article>
  );
}

function ScrollIndicator({ scrollYProgress, total }) {
  const width = useTransform2(scrollYProgress, [0, 1], ["0%", "100%"]);
  return (
    <div className="hs-progress">
      <div className="hs-progress-track">
        <motion.div className="hs-progress-fill" style={{ width }} />
      </div>
      <div className="hs-progress-meta">
        <span className="font-mono">scroll →</span>
        <span className="font-mono">{total} stories</span>
      </div>
    </div>
  );
}

function Process() {
  const { process } = window.PORTFOLIO_DATA;
  const ref = useRef2(null);
  const { scrollYProgress } = useScroll2({ target: ref, offset: ["start end","end start"] });
  const xLeft = useTransform2(scrollYProgress, [0,1], ["10%","-30%"]);
  const xRight = useTransform2(scrollYProgress, [0,1], ["-30%","10%"]);

  return (
    <section id="process" ref={ref} className="proc">
      <div className="eyebrow eyebrow-rust">How I work</div>
      <h2 className="h-serif">A design process that respects <em>users</em>, metrics, and the story around the product.</h2>
      <motion.div style={{ x: xLeft }} className="proc-words proc-words-fill">Discover · Position · Prototype · Validate ·</motion.div>
      <motion.div style={{ x: xRight }} className="proc-words proc-words-out">Discover · Position · Prototype · Validate ·</motion.div>
      <div className="proc-grid">
        {process.map((p,i) => (
          <motion.div key={p.key}
            initial={{ opacity:0, y:40 }}
            whileInView={{ opacity:1, y:0 }}
            viewport={{ once:true, amount:0.3 }}
            transition={{ delay:i*0.08, duration:0.6 }}
            className={`proc-card ${i%2===0 ? "tilt-l":"tilt-r"}`}>
            <div className="proc-meta">
              <div className="proc-idx">0{i+1} / 0{process.length}</div>
              <div className="proc-key">{p.key}</div>
            </div>
            <h3 className="proc-t">{p.title}</h3>
            <p className="proc-b">{p.body}</p>
          </motion.div>
        ))}
      </div>
    </section>
  );
}

window.Work = Work;
window.CaseStudy = CaseStudy;
window.Process = Process;
