/* Hero, Revealed content, Strut, HandLayer, NavRow */

const SECTION_CONTENT = {
  Home: {
    label: "About Me",
    title: "Solving real problems\nthrough engineering.",
    body: "I'm a mechanical engineer with a passion for robotics, automation, and product development. I turn complex challenges into simple, elegant, and efficient solutions.",
    cta: "More About Me",
    lower: { kind: "projects" }
  },
  About: {
    label: "Background",
    title: "Engineer, builder,\nproblem solver.",
    body: "From concept sketches to working prototypes — I bridge mechanical design, embedded systems, and software to build machines that move, sense, and decide.",
    cta: "Read Full Bio",
    lower: {
      kind: "stats",
      label: "By the numbers",
      items: [
        { value: "8+", title: "Years engineering",   note: "Mechanical, controls, embedded" },
        { value: "20", title: "Shipped projects",    note: "Research, industry, personal" },
        { value: "5",  title: "Patents & papers",    note: "Robotics, automation" },
        { value: "12", title: "Tools fluent in",     note: "CAD, FEA, firmware, ML" }
      ]
    }
  },
  Projects: {
    label: "Selected Work",
    title: "Things I've designed,\nbuilt and shipped.",
    body: "A curated selection of robotics, automation, and product engineering projects spanning research, industry, and personal builds.",
    cta: null,
    lower: { kind: "projects" }
  },
  Skills: {
    label: "Capabilities",
    title: "Mechanical, electrical,\nand everything between.",
    body: "Cross-disciplinary fluency: CAD, FEA, controls, embedded firmware, and software — picking the right tool for each problem instead of forcing the same one twice.",
    cta: "See Full Stack",
    lower: {
      kind: "skills",
      label: "Toolkit",
      groups: [
        { title: "Mechanical",  items: ["SolidWorks", "Fusion 360", "Onshape", "FEA / Ansys", "GD&T", "DFM"] },
        { title: "Electrical",  items: ["Altium", "KiCad", "Power systems", "Sensors", "Motor control"] },
        { title: "Firmware",    items: ["C / C++", "STM32", "RTOS", "ROS / ROS2", "CAN bus", "I²C / SPI"] },
        { title: "Software",    items: ["Python", "MATLAB", "TypeScript", "PyTorch", "OpenCV", "Git"] }
      ]
    }
  },
  Experience: {
    label: "Career",
    title: "Where I've worked\nand what I've learned.",
    body: "Roles in robotics R&D, product engineering, and academic research — full résumé behind the button.",
    cta: "View Resume",
    lower: {
      kind: "timeline",
      label: "Highlights",
      items: [
        { period: "2024 — now",  role: "Senior Robotics Engineer", org: "Independent",        note: "Manipulation, perception, controls" },
        { period: "2022 — 2024", role: "Product Engineer",         org: "Hardware Startup",   note: "0→1 consumer robotics" }
      ]
    }
  },
  Contact: {
    label: "Get In Touch",
    title: "Let's build\nsomething together.",
    body: "Open to collaborations, contract work, and full-time roles in robotics and product engineering. Drop me a line.",
    cta: "Send Message",
    lower: {
      kind: "contact",
      label: "Channels",
      items: [
        { method: "Email",    value: "idriz@example.com",            href: "mailto:idriz@example.com" },
        { method: "LinkedIn", value: "linkedin.com/in/idriz",        href: "#" },
        { method: "Instagram", value: "instagram.com/idriz",          href: "#" },
        { method: "Location", value: "Open to relocation / remote",  href: null }
      ]
    }
  }
};

function NavRow({ items, active, flipping, onClick, className = "" }) {
  return (
    <nav className={`nav ${className}`}>
      {items.map((item) =>
      <button
        key={item}
        className={`nav-item ${active === item ? "active" : ""} ${flipping[item] ? "flipping" : ""}`}
        onClick={() => onClick(item)}>
        
          {item}
        </button>
      )}
    </nav>);

}

function Hero({ activeNav, flipping, onNavClick }) {
  return (
    <div className="hero">
      <div className="topbar">
        <div className="brand">
          <span className="brand-mark">I<span className="brand-slash">Z</span></span>
        </div>
        {/* nav lives only on the bottom (revealed) per spec */}
        <div />
      </div>

      <div className="hero-body">
        <div className="eyebrow">Hi, I'm Idriz</div>
        <h1 className="headline">
          <span>I Design.</span>
          <span>Engineer.</span>
          <span>Build.</span>
        </h1>
        <p className="subhead">
          Mechanical Engineer specializing in robotics, automation, and innovative systems.
        </p>
        <button
          className="btn"
          onClick={() => {
            const start = window.scrollY;
            const end = document.documentElement.scrollHeight - window.innerHeight;
            const distance = end - start;
            if (Math.abs(distance) < 1) return;
            const duration = 2400; // ms — slower, more dramatic reveal
            const t0 = performance.now();
            const easeInOut = (x) => x < 0.5 ?
            2 * x * x :
            1 - Math.pow(-2 * x + 2, 2) / 2;
            const step = (now) => {
              const t = Math.min(1, (now - t0) / duration);
              window.scrollTo(0, start + distance * easeInOut(t));
              if (t < 1) requestAnimationFrame(step);
            };
            requestAnimationFrame(step);
          }}>
          
          View My Work <span className="btn-arrow" />
        </button>
      </div>

      <div />

      <div className="scroll-cue">
        <div>00 / SCROLL DOWN</div>
        <div className="scroll-cue-line" />
      </div>
    </div>);

}
window.Hero = Hero;

function PaperPage({ flipKey, children }) {
  // Re-mounts on flipKey change to play paper-flip-in animation
  return (
    <div className="paper-page-wrap">
      <div key={flipKey} className="paper-page">
        {children}
      </div>
    </div>);

}

function LowerSection({ lower, opacity, ty, onOpenProject, activeNav }) {
  if (!lower) return null;

  const wrapStyle = { opacity, transform: `translateY(${ty}px)` };

  if (lower.kind === "projects") {
    // On the Projects page, show the FULL grid (Browse All).
    // On the Home page, show the 3 featured projects.
    const list = activeNav === "Projects" ? (window.ALL_PROJECTS || PROJECTS) : PROJECTS;
    const label = activeNav === "Projects" ? "All Projects" : "Featured Projects";
    return (
      <section className="projects-section" style={wrapStyle}>
        <div className="section-label">{label}</div>
        <div className={`projects ${activeNav === "Projects" ? "projects-all" : ""}`}>
          {list.map((p) =>
          <article
            key={p.id}
            className="project"
            onClick={() => onOpenProject && onOpenProject(p.id)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => { if (e.key === "Enter" && onOpenProject) onOpenProject(p.id); }}
          >
              <div className="project-media" data-tag={p.tag} />
              <div className="project-meta">
                <div>
                  <div className="project-title">{p.title}</div>
                  <div className="project-tags">{p.tags}</div>
                </div>
                <div className="project-arrow">→</div>
              </div>
            </article>
          )}
        </div>
      </section>);
  }

  if (lower.kind === "stats") {
    return (
      <section className="stats-section" style={wrapStyle}>
        <div className="section-label">{lower.label}</div>
        <div className="stats-grid">
          {lower.items.map((it, i) =>
          <div key={i} className="stat-card">
              <div className="stat-value">{it.value}</div>
              <div className="stat-title">{it.title}</div>
              <div className="stat-note">{it.note}</div>
            </div>
          )}
        </div>
      </section>);
  }

  if (lower.kind === "skills") {
    return (
      <section className="skills-section" style={wrapStyle}>
        <div className="section-label">{lower.label}</div>
        <div className="skills-grid">
          {lower.groups.map((g, i) =>
          <div key={i} className="skill-group">
              <div className="skill-group-title">{g.title}</div>
              <div className="skill-chips">
                {g.items.map((s, j) =>
              <span key={j} className="skill-chip">{s}</span>
              )}
              </div>
            </div>
          )}
        </div>
      </section>);
  }

  if (lower.kind === "timeline") {
    return (
      <section className="timeline-section" style={wrapStyle}>
        <div className="section-label">{lower.label}</div>
        <ol className="timeline">
          {lower.items.map((it, i) =>
          <li key={i} className="timeline-item">
              <div className="timeline-period">{it.period}</div>
              <div className="timeline-body">
                <div className="timeline-role">{it.role}</div>
                <div className="timeline-org">{it.org}</div>
                <div className="timeline-note">{it.note}</div>
              </div>
            </li>
          )}
        </ol>
      </section>);
  }

  if (lower.kind === "contact") {
    return (
      <section className="contact-section" style={wrapStyle}>
        <div className="section-label">{lower.label}</div>
        <ul className="contact-list">
          {lower.items.map((it, i) =>
          <li key={i} className="contact-row">
              <div className="contact-method">{it.method}</div>
              {it.href ?
            <a href={it.href} className="contact-value">{it.value}</a> :
            <div className="contact-value">{it.value}</div>
            }
            </li>
          )}
        </ul>
      </section>);
  }

  return null;
}

function ProjectsGridView({ content, opacity, ty, onOpenProject }) {
  const list = window.ALL_PROJECTS || [];
  return (
    <section className="projects-grid-view subview" style={{ opacity, transform: `translateY(${ty}px)` }}>
      <div className="projects-grid-view-header">
        <div className="section-label">{content.label}</div>
        <h2 className="section-title projects-grid-view-title">
          {content.title.split("\n").map((line, i) =>
            <span key={i} style={{ display: "block" }}>{line}</span>
          )}
        </h2>
        <p className="about-body projects-grid-view-body">{content.body}</p>
      </div>

      <div className="projects projects-all">
        {list.map((p) =>
          <article
            key={p.id}
            className="project"
            onClick={() => onOpenProject && onOpenProject(p.id)}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => { if (e.key === "Enter" && onOpenProject) onOpenProject(p.id); }}
          >
            <div className="project-media" data-tag={p.tag} />
            <div className="project-meta">
              <div>
                <div className="project-title">{p.title}</div>
                <div className="project-tags">{p.tags}</div>
              </div>
              <div className="project-arrow">→</div>
            </div>
          </article>
        )}
      </div>
    </section>
  );
}

function RevealedContent({ activeNav, flipping, onNavClick, progress, subView, onCta, onOpenProject, onCloseSubView }) {
  const opacity = Math.max(0, Math.min(1, (progress - 0.2) / 0.5));
  const ty = (1 - opacity) * 24;
  const content = SECTION_CONTENT[activeNav] || SECTION_CONTENT.Home;

  // Map CTA → action. "nav:X" switches the active nav (with flip animation);
  // "sub:Y" opens an in-paper sub-view.
  const ctaTarget = {
    Home:       "nav:About",
    About:      "sub:about-full",
    Projects:   "nav:Projects", // CTA on Projects = "Browse all projects"; render a grid view
    Skills:     "sub:skills-full",
    Experience: "sub:resume",
    Contact:    null
  }[activeNav];

  // Decide what flipKey we use to retrigger the paper-flip animation.
  // When a sub-view is open we tag it so it animates in too.
  const flipKey = subView ? `${activeNav}:${subView.kind}:${subView.id || ""}` : activeNav;

  return (
    <div className="revealed" aria-hidden={progress < 0.2}>
      <div className="case-rim" />

      <PaperPage flipKey={flipKey}>
        {subView ? (
          <SubView
            subView={subView}
            opacity={opacity}
            ty={ty}
            onBack={onCloseSubView}
            onOpenProject={onOpenProject}
          />
        ) : activeNav === "Projects" ? (
          <ProjectsGridView
            content={content}
            opacity={opacity}
            ty={ty}
            onOpenProject={onOpenProject}
          />
        ) : (
          <React.Fragment>
            <section className="about-section" style={{ opacity, transform: `translateY(${ty}px)` }}>
              <div className="about-text">
                <div className="section-label">{content.label}</div>
                <h2 className="section-title">
                  {content.title.split("\n").map((line, i) =>
                  <span key={i} style={{ display: "block" }}>{line}</span>
                  )}
                </h2>
                <p className="about-body">{content.body}</p>
                {content.cta && (
                  <button
                    className="btn btn-light"
                    onClick={() => onCta && onCta(ctaTarget)}
                    disabled={!ctaTarget}
                  >
                    {content.cta} <span className="btn-arrow" />
                  </button>
                )}
              </div>
              <div className="about-visual" data-tag="// robot-arm-render.glb" />
            </section>

            <LowerSection
              lower={content.lower}
              opacity={opacity}
              ty={ty}
              onOpenProject={onOpenProject}
              activeNav={activeNav}
            />
          </React.Fragment>
        )}
      </PaperPage>

      <div className="case-base" style={{ fontWeight: "300", backgroundSize: "cover", borderColor: "rgb(0, 52, 106)", borderWidth: "4px 0px 0px", borderStyle: "solid" }}>
        <NavRow
          items={NAV_ITEMS}
          active={activeNav}
          flipping={flipping}
          onClick={onNavClick}
          className="nav-bottom-bar" />
        
      </div>
    </div>);

}
window.RevealedContent = RevealedContent;

function Strut({ side, extend }) {return null;}
window.Strut = Strut;

function HandLayer({ progress, handCurl, handLift, gripVariant, showHandNote }) {
  // Two-phase motion:
  //   p=0 → 0.5  →  hand reaches DOWN. Hood stays closed.
  //                 gripper travels from center (50vh) to bottom edge (95vh).
  //   p=0.5 → 1  →  gripper grips edge; both rise together as hood opens.
  // Each frame is 400×1024 with hand center aligned across all 4 frames at
  // (280, 880) in source. Displayed at width=220 → height ≈ 563px.
  // We anchor the FINGERTIPS (bottom of hand, source y=1023) to the hood
  // edge so the hand isn't clipped by the viewport bottom.
  // New frames: 576×1024 displayed at 220px wide → 391px tall.
  // Fingertips sit roughly 95% down the image.
  // Responsive: read actual rendered width of .arm-rig and scale anchor proportionally.
  // Default desktop width = 264px → RIG_HEIGHT 469, GRIPPER_OFFSET 445.
  const [armW, setArmW] = React.useState(264);
  React.useEffect(() => {
    const measure = () => {
      const el = document.querySelector('.arm-rig');
      if (el) {
        const w = el.getBoundingClientRect().width;
        if (w > 0) setArmW(w);
      }
    };
    measure();
    const t = setTimeout(measure, 50); // re-measure once styles settle
    window.addEventListener('resize', measure);
    return () => {
      clearTimeout(t);
      window.removeEventListener('resize', measure);
    };
  }, []);
  const armScale = armW / 264;
  const RIG_HEIGHT = 469 * armScale;
  const GRIPPER_OFFSET = 445 * armScale;

  // Phase 1: reach down (no hood movement)
  const reachP = Math.max(0, Math.min(1, progress / 0.5));
  // Phase 2: hood opens, hand rides edge
  const openRaw = Math.max(0, Math.min(1, (progress - 0.5) / 0.5));
  const eased = 1 - Math.pow(1 - openRaw, 2.4);
  const hoodAngle = eased * 95;
  const angleRad = hoodAngle * Math.PI / 180;

  // Reach phase: arm rests at reference position (full arm visible, fingertips
  // low in viewport — matches user's reference). On scroll drops a short
  // distance to grip the hood edge — but the SCROLL DURATION is what makes
  // the motion feel long, not the travel distance.
  const reachStartY = 80; // vh — rest position: full arm visible
  const reachEndY = 100; // vh — keep first/open frame ending at viewport bottom
  // Grip animation only kicks in at the very end of the reach
  const gripThreshold = 0.92;

  // Hood's projected bottom-edge Y as it rotates (hinge at top, around X)
  const edgeYvh = Math.cos(angleRad) * 100;

  // Gripper Y: reach phase climbs to 96vh, then follows the edge
  const gripperYvh =
  openRaw > 0 ?
  edgeYvh :
  reachStartY + (reachEndY - reachStartY) * reachP;

  // Z translation: ride forward with hood as it opens. Smaller base offset
  // to avoid visually shifting the rig away from the hood edge while at rest.
  const edgeZpx = Math.sin(angleRad) * 320;
  const gripperZpx = 5 + edgeZpx;

  // Tilt the rig FORWARD with the hood as it opens (hand stays attached to
  // the hood's bottom edge). Hood rotates by hoodAngle; for the hand to
  // appear glued to the hood edge we apply the same rotation, but we tone
  // it down slightly so the wrist relaxes naturally.
  const tiltDeg = hoodAngle * 0.6;

  // Same grip value used for the hand frame switching — derived once so
  // we can compensate the rig position for per-frame stack offsets.
  const gripValue = Math.max(
    reachP > gripThreshold ? (reachP - gripThreshold) / (1 - gripThreshold) : 0,
    openRaw > 0 ? 1 : 0
  );
  // Perspective compensation: as the rig translates forward (Z+) with the
  // opening hood, the perspective scaling makes the rig appear bigger and
  // pushes the fingertips DOWN in screen space. Counter that here so the
  // fingertips track the hood edge instead of lagging behind.
  // perspective:2200, fingertips ~190px below rig center → vertical drift
  // ≈ 0.09 * Zpx in screen space.
  const perspectiveCompPx = gripperZpx > 5 ? (gripperZpx - 5) * 0.09 : 0;
  const rigTop = `calc(${gripperYvh}vh - ${GRIPPER_OFFSET + perspectiveCompPx}px)`;

  return (
    <div
      style={{
      position: "absolute",
      left: 0, right: 0,
      top: rigTop,
      transformStyle: "preserve-3d",
      transform: `translateZ(${gripperZpx}px) rotateX(${tiltDeg}deg)`,
      transformOrigin: `50% ${GRIPPER_OFFSET}px`,
      pointerEvents: "none",
      zIndex: 40,
      transition: "none"
    }}>
      <RoboticHand
        progress={gripValue}
        gripVariant={gripVariant}
        showSwapNote={showHandNote} />
      
    </div>);

}
window.HandLayer = HandLayer;