/* Idriz Zuncheski — Portfolio app */
const { useState, useEffect, useRef, useMemo } = React;

const NAV_ITEMS = ["Home", "Projects", "About", "Skills", "Experience", "Contact"];

const 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" },
];

const SKILLS = [
  "Mechanical Design",
  "Robotics",
  "Control Systems",
  "Embedded Systems",
  "CAD / Simulation",
  "Python / C++",
];

function App() {
  const [tweaks, setTweak] = useTweaks(window.TWEAK_DEFAULTS || {});
  const {
    accent = "#3b9eff",
    bgTone = "charcoal",
    revealSpeed = 1.0,
    gripVariant = "default",
    density = "default",
    revealMechanic = "hood",
    showHandNote = false,
  } = tweaks;

  // scroll-driven progress 0..1
  const [progress, setProgress] = useState(0);
  // active section in nav
  const [activeNav, setActiveNav] = useState("Home");
  // which nav items are currently mid-flip
  const [flipping, setFlipping] = useState({});
  // optional sub-view inside the paper page (e.g. a specific project detail).
  // Cleared whenever the active nav changes.
  const [subView, setSubView] = useState(null); // null | { kind: "project", id } | { kind: "resume" } | { kind: "skills-full" } | { kind: "about-full" }

  // ESC clears any sub-view
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && subView) setSubView(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [subView]);

  useEffect(() => {
    const onScroll = () => {
      const max = (document.documentElement.scrollHeight - window.innerHeight);
      const raw = max > 0 ? window.scrollY / max : 0;
      // adjust by revealSpeed: higher = reveal happens earlier
      const p = Math.max(0, Math.min(1, raw * revealSpeed));
      setProgress(p);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [revealSpeed]);

  // accent color CSS var
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", accent);
  }, [accent]);

  // Make body scroll length match revealSpeed so progress hits 1.0 exactly
  // at the bottom of the page. Base scroll = 200vh of motion; if revealSpeed
  // is higher, we need less scroll for the same motion.
  useEffect(() => {
    const motionVh = 200 / Math.max(0.1, revealSpeed); // viewport-heights of motion
    document.body.style.minHeight = `calc(100vh + ${motionVh}vh)`;
  }, [revealSpeed]);

  // Two-phase motion:
  //   progress 0 → 0.5  →  hand reaches DOWN to the hood's bottom edge.
  //                        Hood stays closed (hoodAngle = 0).
  //   progress 0.5 → 1  →  hand grips edge, hood opens, both rise together.
  const reachP = Math.max(0, Math.min(1, progress / 0.5));
  const openRaw = Math.max(0, Math.min(1, (progress - 0.5) / 0.5));
  // ease-out for the open phase
  const eased = 1 - Math.pow(1 - openRaw, 2.4);
  const hoodAngle = eased * 95;

  // Strut extension follows hood angle
  const strutExtend = eased; // 0..1

  // Iris radius for iris mechanic
  const irisR = eased * 110; // % radius

  // The hand grips while progress < 0.55, then lifts away after
  const handCurl = Math.min(1, progress / 0.55);
  const handLift = Math.max(0, (progress - 0.55) / 0.45);

  // Click nav: trigger flip on the clicked item, then promote it.
  // Also clears any sub-view (project detail / full resume).
  const onNavClick = (item) => {
    setFlipping(f => ({ ...f, [item]: true }));
    setTimeout(() => {
      setActiveNav(item);
      setSubView(null);
      setFlipping(f => ({ ...f, [item]: false }));
    }, 300);
  };

  // CTA buttons in each section navigate via nav (with the same flip animation)
  // or open an in-paper sub-view.
  const onCta = (target) => {
    if (!target) return;
    if (target.startsWith("nav:")) {
      onNavClick(target.slice(4));
    } else if (target === "sub:resume") {
      setSubView({ kind: "resume" });
    } else if (target === "sub:skills-full") {
      setSubView({ kind: "skills-full" });
    } else if (target === "sub:about-full") {
      setSubView({ kind: "about-full" });
    }
  };

  const openProject = (id) => setSubView({ kind: "project", id });
  const closeSubView = () => setSubView(null);

  const themeClass =
    bgTone === "navy" ? "theme-navy" :
    bgTone === "black" ? "theme-black" : "";

  const densityClass =
    density === "cozy" ? "density-cozy" :
    density === "spacious" ? "density-spacious" : "";

  return (
    <div className={`root ${themeClass} ${densityClass} reveal-${revealMechanic}`}
         style={{ "--iris-r": `${irisR}%` }}>

      <div className="stage">

        {/* ===== Bottom revealed content ===== */}
        <RevealedContent
          activeNav={activeNav}
          flipping={flipping}
          onNavClick={onNavClick}
          progress={progress}
          subView={subView}
          onCta={onCta}
          onOpenProject={openProject}
          onCloseSubView={closeSubView}
        />

        {/* ===== The hood (opens like a real hood — hinged at top, bottom
            edge rotates TOWARD viewer so the dark underside faces us). ===== */}
        <div className="hood" style={{
          transform: `rotateX(${hoodAngle}deg)`,
          boxShadow: progress > 0.05
            ? `0 ${20 + eased * 60}px ${40 + eased * 80}px rgba(0,0,0,${0.4 + eased * 0.4})`
            : "none"
        }}>
          {/* hinge */}
          <div className="hinge">
            <div className="hinge-bolt" />
            <div className="hinge-bolt" />
          </div>

          {/* underside (visible after hood rotates past ~25deg) */}
          <div className="hood-underside" style={{
            opacity: progress > 0.15 ? 1 : 0
          }} />

          {/* face — the hero */}
          <div className="hood-face">
            <Hero
              activeNav={activeNav}
              flipping={flipping}
              onNavClick={onNavClick}
            />
          </div>
        </div>

        {/* ===== Hydraulic struts — between hood and base ===== */}
        <Strut side="left"  extend={strutExtend} />
        <Strut side="right" extend={strutExtend} />

        {/* ===== The robotic hand — sits in front, gripping the hood edge ===== */}
        <HandLayer
          progress={progress}
          handCurl={handCurl}
          handLift={handLift}
          gripVariant={gripVariant}
          showHandNote={showHandNote}
        />

      </div>

      {/* Tweaks panel */}
      <TweaksPanelMount tweaks={tweaks} setTweak={setTweak} />
    </div>
  );
}

window.App = App;
