
// Skills section — three variants: marquee, orbital, grid

const TECHS = [
  "React", "JavaScript", "TypeScript", "CSS", "Tailwind",
  "Figma", "PHP", "Laravel", "Java", "C#",
  "SQL", "PostgreSQL", "Redis", "Supabase", "Docker",
  "Git", "Linux", "CI/CD", "Vercel", "Agile",
];

const TECH_CATEGORIES = [
  { label: "Frontend", techs: ["React", "JavaScript", "TypeScript", "CSS", "Tailwind", "Figma"] },
  { label: "Backend", techs: ["PHP", "Laravel", "Java", "C#", "SQL"] },
  { label: "Infra & Tools", techs: ["Git", "Linux", "Docker", "CI/CD", "PostgreSQL", "Redis", "Supabase", "Vercel", "Agile"] },
];

// ─── VARIANT 1: Infinite Marquee ─────────────────────────────────────────────

function MarqueeRow({ items, reverse = false, speed = 40 }) {
  const doubled = [...items, ...items];
  return (
    <div style={{ overflow: "hidden", maskImage: "linear-gradient(to right, transparent 0%, black 8%, black 92%, transparent 100%)" }}>
      <div style={{
        display: "flex",
        gap: "clamp(32px, 4vw, 60px)",
        width: "max-content",
        animation: `marquee${reverse ? "Rev" : ""} ${speed}s linear infinite`,
      }}>
        {doubled.map((tech, i) => (
          <span key={i} style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontWeight: 300,
            fontSize: "clamp(28px, 3.5vw, 52px)",
            color: i % 4 === 0 ? "#2a2a2a" : i % 3 === 0 ? "#555" : "#1e1e1e",
            letterSpacing: "-0.01em",
            whiteSpace: "nowrap",
            transition: "color 0.3s ease",
            flexShrink: 0,
          }}
          onMouseEnter={e => { e.currentTarget.style.color = "#ededeb"; }}
          onMouseLeave={e => { e.currentTarget.style.color = i % 4 === 0 ? "#2a2a2a" : i % 3 === 0 ? "#555" : "#1e1e1e"; }}
          >
            {tech}
          </span>
        ))}
      </div>
    </div>
  );
}

function SkillsMarquee() {
  const row1 = TECHS.slice(0, 10);
  const row2 = TECHS.slice(10);
  const row3 = [...TECHS.slice(5, 15)];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "clamp(20px, 3vh, 36px)", paddingTop: "clamp(24px, 4vh, 44px)", paddingBottom: "clamp(24px, 4vh, 44px)" }}>
      <MarqueeRow items={row1} speed={38} />
      <MarqueeRow items={row2} reverse speed={52} />
      <MarqueeRow items={row3} speed={44} />
    </div>
  );
}

// ─── VARIANT 2: Orbital rings ─────────────────────────────────────────────────

function OrbitalCloud() {
  const canvasRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const mouseRef = React.useRef({ x: -1, y: -1 });
  const pausedRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    let W, H, cx, cy;

    const rings = [
      { techs: TECH_CATEGORIES[0].techs, label: "Frontend", r: 0.30, speed: 0.008,  angle: 0, color: "#ededeb" },
      { techs: TECH_CATEGORIES[1].techs, label: "Backend",  r: 0.44, speed: -0.005, angle: Math.PI / 5, color: "#aaa" },
      { techs: TECH_CATEGORIES[2].techs, label: "Infra",    r: 0.58, speed: 0.003,  angle: Math.PI / 3, color: "#666" },
    ];

    const resize = () => {
      W = canvas.width = canvas.clientWidth;
      H = canvas.height = canvas.clientHeight;
      cx = W / 2; cy = H / 2;
    };
    resize();
    window.addEventListener("resize", resize);

    const onMouseMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouseRef.current = { x: e.clientX - rect.left, y: e.clientY - rect.top };
    };
    const onMouseLeave = () => { mouseRef.current = { x: -1, y: -1 }; pausedRef.current = null; };
    canvas.addEventListener("mousemove", onMouseMove);
    canvas.addEventListener("mouseleave", onMouseLeave);

    const t0 = performance.now();
    const render = () => {
      const elapsed = (performance.now() - t0) / 1000;
      ctx.clearRect(0, 0, W, H);

      const scale = Math.min(W, H);
      pausedRef.current = null;

      rings.forEach((ring, ri) => {
        const rPx = ring.r * scale * 0.5;
        const count = ring.techs.length;
        let hoveredIdx = -1;

        ring.techs.forEach((_, ti) => {
          const a = ring.angle + (ti / count) * Math.PI * 2;
          const tx = cx + Math.cos(a) * rPx;
          const ty = cy + Math.sin(a) * rPx;
          const d = Math.hypot(tx - mouseRef.current.x, ty - mouseRef.current.y);
          if (d < 44) { hoveredIdx = ti; pausedRef.current = ri; }
        });

        const isRingPaused = pausedRef.current === ri;
        if (!isRingPaused) ring.angle += ring.speed;

        ctx.beginPath();
        ctx.arc(cx, cy, rPx, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(255,255,255,0.04)`;
        ctx.lineWidth = 1;
        ctx.stroke();

        const labelA = ring.angle + Math.PI * 1.5;
        const lx = cx + Math.cos(labelA) * (rPx + 18);
        const ly = cy + Math.sin(labelA) * (rPx + 18);
        ctx.font = `300 9px 'DM Mono', monospace`;
        ctx.fillStyle = "rgba(255,255,255,0.15)";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillText(ring.label.toUpperCase(), lx, ly);

        ring.techs.forEach((tech, ti) => {
          const a = ring.angle + (ti / count) * Math.PI * 2;
          const tx = cx + Math.cos(a) * rPx;
          const ty = cy + Math.sin(a) * rPx;
          const isHovered = ti === hoveredIdx;
          const fontSize = isHovered ? 14 : 11;

          ctx.save();
          ctx.translate(tx, ty);
          ctx.font = `300 ${fontSize}px 'DM Mono', monospace`;
          ctx.fillStyle = isHovered ? "#ededeb" : `rgba(255,255,255,${0.15 + ri * 0.08})`;
          ctx.textAlign = "center";
          ctx.textBaseline = "middle";
          if (isHovered) {
            ctx.shadowColor = "rgba(237,237,235,0.5)";
            ctx.shadowBlur = 12;
          }
          ctx.fillText(tech, 0, 0);
          ctx.restore();
        });
      });

      ctx.beginPath();
      ctx.arc(cx, cy, 3, 0, Math.PI * 2);
      ctx.fillStyle = "#222";
      ctx.fill();
      ctx.beginPath();
      ctx.arc(cx, cy, 1.5, 0, Math.PI * 2);
      ctx.fillStyle = "#555";
      ctx.fill();

      rafRef.current = requestAnimationFrame(render);
    };
    rafRef.current = requestAnimationFrame(render);

    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener("resize", resize);
      canvas.removeEventListener("mousemove", onMouseMove);
      canvas.removeEventListener("mouseleave", onMouseLeave);
    };
  }, []);

  return <canvas ref={canvasRef} style={{ width: "100%", height: "100%", display: "block", cursor: "none" }} />;
}

// ─── VARIANT 3: Editorial grid ────────────────────────────────────────────────

const PROFICIENCY = {
  "JavaScript": 0.8, "TypeScript": 0.7, "React": 0.7, "CSS": 0.85, "Tailwind": 0.75, "Figma": 0.65,
  "PHP": 0.85, "Laravel": 0.8, "Java": 0.8, "C#": 0.7, "SQL": 0.85,
  "PostgreSQL": 0.75, "Redis": 0.5, "Supabase": 0.6, "Docker": 0.65,
  "Git": 0.9, "Linux": 0.7, "CI/CD": 0.6, "Vercel": 0.65, "Agile": 0.7,
};

function GridCategory({ cat, delay }) {
  const ref = React.useRef(null);
  const [vis, setVis] = React.useState(false);

  React.useEffect(() => {
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setTimeout(() => setVis(true), delay); io.disconnect(); } }, { threshold: 0.1 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [delay]);

  return (
    <div ref={ref} style={{ opacity: vis ? 1 : 0, transform: vis ? "translateY(0)" : "translateY(20px)", transition: "all 0.7s cubic-bezier(0.16,1,0.3,1)" }}>
      <p style={{ fontFamily: "'DM Mono', monospace", fontSize: 9, letterSpacing: "0.28em", textTransform: "uppercase", color: "#2a2a2a", marginBottom: 20 }}>
        {cat.label}
      </p>
      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {cat.techs.map((tech, i) => {
          const pct = PROFICIENCY[tech] || 0.7;
          return (
            <div key={tech} style={{
              display: "grid",
              gridTemplateColumns: "120px 1fr auto",
              alignItems: "center",
              gap: 16,
              padding: "12px 0",
              borderBottom: "1px solid #111",
              opacity: vis ? 1 : 0,
              transform: vis ? "translateX(0)" : "translateX(-12px)",
              transition: `all 0.6s cubic-bezier(0.16,1,0.3,1) ${delay + i * 45}ms`,
            }}>
              <span style={{ fontFamily: "'DM Sans', sans-serif", fontWeight: 300, fontSize: "clamp(12px, 1vw, 14px)", color: "#888" }}>{tech}</span>
              <div style={{ height: 1, background: "#111", position: "relative", overflow: "hidden" }}>
                <div style={{
                  position: "absolute", left: 0, top: 0, bottom: 0,
                  background: "#2e2e2e",
                  width: vis ? `${pct * 100}%` : "0%",
                  transition: `width 1.2s cubic-bezier(0.16,1,0.3,1) ${delay + i * 45 + 200}ms`,
                }} />
              </div>
              <span style={{ fontFamily: "'DM Mono', monospace", fontSize: 9, color: "#222", letterSpacing: "0.1em" }}>
                {Math.round(pct * 100)}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function SkillsGrid() {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
      gap: "clamp(40px, 6vw, 80px)",
      padding: "clamp(32px, 5vh, 60px) clamp(24px, 8vw, 120px)",
    }}>
      {TECH_CATEGORIES.map((cat, i) => (
        <GridCategory key={cat.label} cat={cat} delay={i * 120} />
      ))}
    </div>
  );
}

// ─── Section wrapper ──────────────────────────────────────────────────────────

function SkillsSection({ variant = "marquee" }) {
  const { t } = useI18n();
  const s = t.skills;

  return (
    <section
      id="skills"
      data-screen-label="03 Skills"
      style={{
        padding: "clamp(80px, 12vh, 140px) 0",
        minHeight: variant === "orbital" ? "95vh" : "auto",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <div style={{ padding: "0 clamp(24px, 8vw, 120px)", marginBottom: "clamp(32px, 5vh, 56px)" }}>
        <RevealText delay={0} className="section-label"><span>{s.label}</span></RevealText>
        <RevealWords delay={120} className="section-title" style={{ marginTop: 16 }}>{s.title}</RevealWords>
        <RevealText delay={240}><p className="section-subtitle">{s.subtitle}</p></RevealText>
      </div>

      {variant === "marquee" && (
        <div style={{ borderTop: "1px solid #111", borderBottom: "1px solid #111", overflow: "hidden" }}>
          <SkillsMarquee />
        </div>
      )}

      {variant === "orbital" && (
        <div style={{ flex: 1, minHeight: "clamp(400px, 55vh, 640px)", position: "relative", borderTop: "1px solid #111", borderBottom: "1px solid #111" }}>
          <OrbitalCloud />
        </div>
      )}

      {variant === "grid" && (
        <div style={{ borderTop: "1px solid #111" }}>
          <SkillsGrid />
        </div>
      )}
    </section>
  );
}

Object.assign(window, { SkillsSection });
