/* In-paper sub-views (rendered INSIDE the revealed paper-page).
   - About full bio
   - Skills full stack
   - Resume full
   - Project detail
   Each takes onBack to return to the parent section. */

const PROJECT_DETAILS = {
  1: {
    title: "Project One",
    tags: "Robotics · Control Systems",
    year: "2024",
    role: "Lead Mechanical + Controls",
    summary:
      "A 6-DOF manipulator built around a custom harmonic-drive joint, paired with a vision system for sub-millimeter pick-and-place in cluttered scenes.",
    sections: [
      { h: "Problem",  p: "Off-the-shelf arms couldn't reach the cycle time we needed without sacrificing accuracy on small SKUs. We needed a fast, repeatable, easy-to-service alternative that fit the same cell footprint." },
      { h: "Approach", p: "Designed a harmonic-drive joint family with shared electronics and firmware, then built a planner around an ICP-guided perception loop. Spent a lot of time on the gripper — the geometry change between SKUs is where most of the cycle time was hiding." },
      { h: "Outcome",  p: "Cycle time down 38%, repeatability ±0.15mm, MTBF up 2.1×. Three units now in production cells; a fourth is in qualification." }
    ],
    stats: [
      { k: "DOF", v: "6" },
      { k: "Repeatability", v: "±0.15mm" },
      { k: "Payload", v: "3kg" },
      { k: "Cycle", v: "0.8s" }
    ]
  },
  2: {
    title: "Project Two",
    tags: "Automation · CAD · Embedded",
    year: "2023",
    role: "Product Engineer",
    summary:
      "Tabletop automation cell for a hardware startup — turned a manual assembly step into a one-button operation, designed for a non-engineer operator.",
    sections: [
      { h: "Problem",  p: "A bottleneck assembly step required two skilled operators and was the largest source of warranty returns. Replacing it with a fixture wasn't enough — the variability in incoming parts demanded closed-loop adjustment." },
      { h: "Approach", p: "Iterated on three fixture concepts in a week, picked the one that absorbed part variation passively, then added a vision check for go/no-go and a small linear stage to dial in the alignment." },
      { h: "Outcome",  p: "One-operator cell, 22-second takt, warranty rate down 71% on the affected SKU. Now the reference design for the next two product lines." }
    ],
    stats: [
      { k: "Takt", v: "22s" },
      { k: "Operators", v: "1" },
      { k: "Yield", v: "99.4%" },
      { k: "Footprint", v: "0.8m²" }
    ]
  },
  3: {
    title: "Project Three",
    tags: "Robotics · Sensors · Nav",
    year: "2022",
    role: "R&D Engineer",
    summary:
      "An autonomous mobile platform for warehouse inventory — built around a tightly integrated sensor stack and a planner that gracefully degrades when one sensor goes blind.",
    sections: [
      { h: "Problem",  p: "The fleet's existing nav stack stalled in aisles where forklifts kicked up dust or where shelves were too sparse for SLAM to lock. We needed reliability across a long tail of hostile cases, not a higher score on the easy ones." },
      { h: "Approach", p: "Fused 2D LiDAR, depth, and wheel odometry with a learned uncertainty estimator that gates which signals the planner trusts. Hardware-wise, repackaged the sensor head so all three sensors share a calibration jig." },
      { h: "Outcome",  p: "97% mission completion across the previously failing aisles, with no reduction in nominal-case throughput." }
    ],
    stats: [
      { k: "Speed", v: "1.6 m/s" },
      { k: "Run time", v: "8h" },
      { k: "Sensors", v: "LiDAR · Depth · IMU" },
      { k: "Uptime", v: "97%" }
    ]
  }
};
window.PROJECT_DETAILS = PROJECT_DETAILS;

const ALL_PROJECTS = [
  { id: 1, title: "Project One",   tags: "Robotics · Control Systems",   tag: "// project-render-01" },
  { id: 2, title: "Project Two",   tags: "Automation · CAD · Embedded",  tag: "// project-render-02" },
  { id: 3, title: "Project Three", tags: "Robotics · Sensors · Nav",     tag: "// project-render-03" },
  { id: 4, title: "Project Four",  tags: "End-Effectors · DFM",          tag: "// project-render-04" },
  { id: 5, title: "Project Five",  tags: "Firmware · CAN · Motor Ctrl",  tag: "// project-render-05" },
  { id: 6, title: "Project Six",   tags: "Research · Locomotion",        tag: "// project-render-06" }
];
window.ALL_PROJECTS = ALL_PROJECTS;

function SubViewHeader({ eyebrow, title, onBack }) {
  return (
    <div className="subview-header">
      <button className="subview-back" onClick={onBack} aria-label="Back">
        <span className="page-back-arrow">←</span> Back
      </button>
      <div className="subview-eyebrow section-label">{eyebrow}</div>
      <h2 className="section-title subview-title">{title}</h2>
    </div>
  );
}

function AboutFullSubView({ onBack, opacity, ty }) {
  return (
    <section className="subview" style={{ opacity, transform: `translateY(${ty}px)` }}>
      <SubViewHeader eyebrow="About" title="More about me." onBack={onBack} />

      <div className="about-page-grid">
        <div className="about-page-lede">
          <p>
            I'm Idriz — a mechanical engineer who spends most of his time at
            the messy intersection of hardware, firmware, and the planners
            that make them behave like one machine. Robotics is what I keep
            coming back to.
          </p>
          <p>
            I started out drawing harmonic drives in CAD as a graduate student,
            shipped my first product as a one-person mechanical team at a
            hardware startup, and now lead robotics R&amp;D projects from a
            sketch through to qualification.
          </p>
          <p>
            Outside of work I build small machines for the sake of building
            small machines, and write occasionally about the parts of
            engineering nobody tells you about until you've already learned
            the hard way.
          </p>
        </div>

        <aside className="about-page-side">
          <div className="about-fact"><div className="about-fact-k">Based</div><div className="about-fact-v">Open to relocation / remote</div></div>
          <div className="about-fact"><div className="about-fact-k">Education</div><div className="about-fact-v">M.Sc. Mechanical Engineering</div></div>
          <div className="about-fact"><div className="about-fact-k">Languages</div><div className="about-fact-v">English · Macedonian · Albanian</div></div>
          <div className="about-fact"><div className="about-fact-k">Currently</div><div className="about-fact-v">Senior Robotics Engineer</div></div>
        </aside>
      </div>

      <div className="section-label" style={{ marginTop: 24 }}>By the numbers</div>
      <div className="stats-grid">
        <div className="stat-card"><div className="stat-value">8+</div><div className="stat-title">Years engineering</div><div className="stat-note">Mechanical, controls, embedded</div></div>
        <div className="stat-card"><div className="stat-value">20</div><div className="stat-title">Shipped projects</div><div className="stat-note">Research, industry, personal</div></div>
        <div className="stat-card"><div className="stat-value">5</div><div className="stat-title">Patents &amp; papers</div><div className="stat-note">Robotics, automation</div></div>
        <div className="stat-card"><div className="stat-value">12</div><div className="stat-title">Tools fluent in</div><div className="stat-note">CAD, FEA, firmware, ML</div></div>
      </div>
    </section>
  );
}

function SkillsFullSubView({ onBack, opacity, ty }) {
  const groups = [
    { title: "Mechanical", items: [
      { name: "SolidWorks", level: 5 }, { name: "Fusion 360", level: 4 },
      { name: "Onshape", level: 4 },    { name: "FEA / Ansys", level: 4 },
      { name: "GD&T", level: 5 },       { name: "DFM / DFA", level: 4 }
    ]},
    { title: "Electrical", items: [
      { name: "Altium", level: 4 }, { name: "KiCad", level: 4 },
      { name: "Power systems", level: 4 }, { name: "Sensors", level: 5 },
      { name: "Motor control", level: 4 }
    ]},
    { title: "Firmware", items: [
      { name: "C / C++", level: 5 }, { name: "STM32", level: 4 },
      { name: "RTOS", level: 4 },    { name: "ROS / ROS2", level: 5 },
      { name: "CAN bus", level: 4 }, { name: "I²C / SPI", level: 5 }
    ]},
    { title: "Software", items: [
      { name: "Python", level: 5 },    { name: "MATLAB", level: 4 },
      { name: "TypeScript", level: 4 },{ name: "PyTorch", level: 3 },
      { name: "OpenCV", level: 4 },    { name: "Git", level: 5 }
    ]}
  ];

  return (
    <section className="subview" style={{ opacity, transform: `translateY(${ty}px)` }}>
      <SubViewHeader eyebrow="Capabilities" title="The full stack." onBack={onBack} />

      <div className="skills-page-grid">
        {groups.map((g, gi) => (
          <div key={gi} className="skill-page-group">
            <div className="skill-page-group-title">{g.title}</div>
            <ul className="skill-page-list">
              {g.items.map((it, i) => (
                <li key={i} className="skill-page-row">
                  <span className="skill-page-name">{it.name}</span>
                  <span className="skill-page-bar" aria-label={`Level ${it.level} of 5`}>
                    {[1,2,3,4,5].map((n) => (
                      <span key={n} className={`skill-page-pip ${n <= it.level ? "filled" : ""}`} />
                    ))}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </section>
  );
}

function ResumeSubView({ onBack, opacity, ty }) {
  const exp = [
    { period: "2024 — present", role: "Senior Robotics Engineer", org: "Independent / Contract",
      bullets: [
        "Lead manipulation, perception, and controls on a 6-DOF platform.",
        "Designed a harmonic-drive joint family — shared electronics across SKUs.",
        "Cut cycle time 38% on the reference cell while improving repeatability."
      ] },
    { period: "2022 — 2024", role: "Product Engineer", org: "Hardware Startup",
      bullets: [
        "0→1 mechanical lead on a consumer robotics product (3 SKUs shipped).",
        "Owned DFM, supplier qualification, and pilot production tooling.",
        "Reduced warranty returns 71% on the bottleneck assembly via a one-operator cell."
      ] },
    { period: "2020 — 2022", role: "R&D Engineer", org: "Industrial Lab",
      bullets: [
        "Built automation cells and end-effectors for high-mix, low-volume lines.",
        "Wrote a sensor-fusion stack for AMRs that hit 97% mission completion."
      ] },
    { period: "2018 — 2020", role: "Graduate Researcher", org: "University",
      bullets: [
        "M.Sc. thesis on bio-inspired locomotion; co-authored 2 conference papers.",
        "Built two legged-robot prototypes from scratch — mechanical, firmware, controls."
      ] }
  ];

  return (
    <section className="subview" style={{ opacity, transform: `translateY(${ty}px)` }}>
      <SubViewHeader eyebrow="Career" title="Full résumé." onBack={onBack} />

      <div className="resume-actions">
        <a className="btn btn-light" href="#" onClick={(e) => e.preventDefault()}>
          Download PDF <span className="btn-arrow" />
        </a>
      </div>

      <div className="section-label" style={{ marginTop: 16 }}>Experience</div>
      <ol className="timeline timeline-full">
        {exp.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>
              <ul className="resume-bullets">
                {it.bullets.map((b, j) => <li key={j}>{b}</li>)}
              </ul>
            </div>
          </li>
        ))}
      </ol>

      <div className="section-label" style={{ marginTop: 32 }}>Education</div>
      <ol className="timeline">
        <li className="timeline-item">
          <div className="timeline-period">2018 — 2020</div>
          <div className="timeline-body">
            <div className="timeline-role">M.Sc. Mechanical Engineering</div>
            <div className="timeline-org">University</div>
            <div className="timeline-note">Thesis: bio-inspired locomotion</div>
          </div>
        </li>
        <li className="timeline-item">
          <div className="timeline-period">2014 — 2018</div>
          <div className="timeline-body">
            <div className="timeline-role">B.Sc. Mechanical Engineering</div>
            <div className="timeline-org">University</div>
            <div className="timeline-note">Minor in Electrical Engineering</div>
          </div>
        </li>
      </ol>
    </section>
  );
}

function ProjectDetailSubView({ id, onBack, onOpenProject, opacity, ty }) {
  const data = PROJECT_DETAILS[id];
  if (!data) {
    return (
      <section className="subview" style={{ opacity, transform: `translateY(${ty}px)` }}>
        <SubViewHeader eyebrow="Case Study" title={`Project ${id}`} onBack={onBack} />
        <p className="page-lede">Coming soon — full case study in progress.</p>
      </section>
    );
  }
  const others = ALL_PROJECTS.filter((p) => p.id !== id && PROJECT_DETAILS[p.id]).slice(0, 2);

  return (
    <section className="subview" style={{ opacity, transform: `translateY(${ty}px)` }}>
      <SubViewHeader eyebrow={`Case Study · ${data.year}`} title={data.title} onBack={onBack} />

      <div className="project-detail-meta">
        <div><div className="about-fact-k">Tags</div><div className="about-fact-v">{data.tags}</div></div>
        <div><div className="about-fact-k">Role</div><div className="about-fact-v">{data.role}</div></div>
        <div><div className="about-fact-k">Year</div><div className="about-fact-v">{data.year}</div></div>
      </div>

      <div className="project-detail-hero" data-tag={`// ${data.title.toLowerCase().replace(/\s+/g, "-")}-render.glb`} />

      <p className="project-detail-summary">{data.summary}</p>

      <div className="project-detail-stats">
        {data.stats.map((s, i) => (
          <div key={i} className="pdetail-stat">
            <div className="pdetail-stat-k">{s.k}</div>
            <div className="pdetail-stat-v">{s.v}</div>
          </div>
        ))}
      </div>

      <div className="project-detail-sections">
        {data.sections.map((s, i) => (
          <section key={i} className="pdetail-section">
            <div className="section-label">{String(i + 1).padStart(2, "0")} · {s.h}</div>
            <p>{s.p}</p>
          </section>
        ))}
      </div>

      {others.length > 0 && (
        <div className="pdetail-next">
          <div className="section-label">Other Projects</div>
          <div className="pdetail-next-grid">
            {others.map((p) => (
              <button key={p.id} className="pdetail-next-card" onClick={() => onOpenProject(p.id)}>
                <div className="pdetail-next-title">{p.title}</div>
                <div className="pdetail-next-tags">{p.tags}</div>
                <div className="project-arrow">→</div>
              </button>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

function SubView({ subView, onBack, onOpenProject, opacity, ty }) {
  if (!subView) return null;
  if (subView.kind === "about-full")   return <AboutFullSubView   onBack={onBack} opacity={opacity} ty={ty} />;
  if (subView.kind === "skills-full")  return <SkillsFullSubView  onBack={onBack} opacity={opacity} ty={ty} />;
  if (subView.kind === "resume")       return <ResumeSubView      onBack={onBack} opacity={opacity} ty={ty} />;
  if (subView.kind === "project")      return <ProjectDetailSubView id={subView.id} onBack={onBack} onOpenProject={onOpenProject} opacity={opacity} ty={ty} />;
  return null;
}
window.SubView = SubView;
