/* Skills graph + Projects + Case study */

const { useState: useState2, useEffect: useEffect2, useRef: useRef2, useMemo: useMemo2 } = React;

function Skills({ t, lang }) {
  const [secRef, secIn] = window.PortfolioPart1.useReveal();
  const [active, setActive] = useState2(null);
  const wrapRef = useRef2(null);
  const [size, setSize] = useState2({ w: 1000, h: 640 });

  useEffect2(() => {
    const update = () => {
      if (!wrapRef.current) return;
      const r = wrapRef.current.getBoundingClientRect();
      setSize({ w: r.width, h: r.height });
    };
    update();
    const ro = new ResizeObserver(update);
    if (wrapRef.current) ro.observe(wrapRef.current);
    return () => ro.disconnect();
  }, []);

  // Auto-rotate active node when no hover
  const [auto, setAuto] = useState2(0);
  useEffect2(() => {
    if (active) return;
    const id = setInterval(() => setAuto((i) => (i + 1) % SKILLS.length), 2200);
    return () => clearInterval(id);
  }, [active]);

  const activeId = active || SKILLS[auto].id;
  const activeSkill = SKILLS.find(s => s.id === activeId);

  const pos = (s) => ({ left: (s.x / 100) * size.w, top: (s.y / 100) * size.h });

  return (
    <section id="skills" ref={secRef}>
      <div className={`section-tag reveal ${secIn ? 'in' : ''}`}>{t.skills.tag}</div>
      <h2 className={`section-title reveal d1 ${secIn ? 'in' : ''}`}>
        {t.skills.title.map((seg, i) => typeof seg === 'string' ? <span key={i}>{seg}</span> : seg)}
      </h2>
      <p className={`reveal d2 ${secIn ? 'in' : ''}`} style={{ color: 'var(--fg-dim)', marginTop: '-40px', marginBottom: '40px', fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>
        {t.skills.sub}
      </p>

      <div className={`skills-wrap reveal d3 ${secIn ? 'in' : ''}`} ref={wrapRef}>
        <div className="skills-grid-bg" />

        <svg className="skills-svg" width={size.w} height={size.h}>
          {SKILL_EDGES.map(([a, b], i) => {
            const sa = SKILLS.find(s => s.id === a);
            const sb = SKILLS.find(s => s.id === b);
            if (!sa || !sb) return null;
            const pa = pos(sa), pb = pos(sb);
            const live = activeId === a || activeId === b;
            return (
              <path
                key={i}
                d={`M ${pa.left} ${pa.top} L ${pb.left} ${pb.top}`}
                className={live ? 'live' : ''}
              />
            );
          })}
        </svg>

        {SKILLS.map((s) => {
          const p = pos(s);
          const isCore = s.id === 'core';
          return (
            <div
              key={s.id}
              className={`skill-node ${activeId === s.id ? 'active' : ''}`}
              style={{ left: p.left, top: p.top }}
              onMouseEnter={() => setActive(s.id)}
              onMouseLeave={() => setActive(null)}
            >
              <div className="glyph" style={isCore ? {
                width: 72, height: 72, fontSize: 26,
                background: 'radial-gradient(circle, rgba(0,229,255,.25), rgba(10,13,18,.95))',
                borderColor: 'var(--accent)',
                boxShadow: '0 0 32px rgba(0,229,255,.5), inset 0 0 16px rgba(0,229,255,.2)',
                color: 'var(--accent)'
              } : {}}>
                {s.glyph}
              </div>
              <div className="lbl">{s.name}</div>
              <div className="cat">{t.skills.categories[s.cat] || s.cat}</div>
            </div>
          );
        })}

        <div className="skills-counter">
          <span>{t.skills.detail.title}</span> · <b>{SKILLS.length - 1}</b> nodes · <b>{SKILL_EDGES.length}</b> edges
        </div>

        <div className="skills-detail">
          <div className="name">{activeSkill.name}</div>
          <div><span className="k">{t.skills.detail.cat} · </span><span className="v">{t.skills.categories[activeSkill.cat] || activeSkill.cat}</span></div>
          <div><span className="k">{t.skills.detail.ctx} · </span>{activeSkill.ctx[lang] || activeSkill.ctx.pt}</div>
        </div>
      </div>
    </section>
  );
}

/* ─── Project visual decorations ─── */
function ProjectVisual({ id }) {
  if (id === 'herbs') {
    return (
      <svg className="visual-svg" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice">
        <g stroke="rgba(0,255,163,.4)" fill="none" strokeWidth="1">
          {Array.from({length: 8}).map((_, i) => (
            <path key={i} d={`M ${50 + i*40} 280 Q ${50 + i*40} ${180 - Math.sin(i)*30} ${50 + i*40 + Math.cos(i)*20} ${100 + Math.sin(i)*40}`} />
          ))}
          {Array.from({length: 16}).map((_, i) => (
            <circle key={'c'+i} cx={40 + (i%4)*100} cy={50 + Math.floor(i/4)*60} r={2 + (i%3)} fill="rgba(0,255,163,.3)" />
          ))}
        </g>
      </svg>
    );
  }
  if (id === 'estoque') {
    return (
      <svg className="visual-svg" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice">
        <g stroke="rgba(124,92,255,.4)" fill="none" strokeWidth="1">
          {Array.from({length: 7}).map((_, r) =>
            Array.from({length: 10}).map((_, c) => (
              <rect key={`${r}-${c}`} x={20 + c*38} y={20 + r*36} width="32" height="28" rx="2" opacity={Math.random() > .3 ? 1 : .3} />
            ))
          )}
        </g>
      </svg>
    );
  }
  if (id === 'cnr') {
    return (
      <svg className="visual-svg" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice">
        <g stroke="rgba(0,229,255,.5)" fill="none" strokeWidth="1.2">
          <path d="M 50 150 Q 200 50 350 150 T 650 150" />
          <path d="M 50 170 Q 200 80 350 170" opacity=".5" />
          <path d="M 50 190 Q 200 110 350 190" opacity=".3" />
          <text x="50" y="100" fill="rgba(0,229,255,.6)" fontSize="36" fontFamily="Space Grotesk">CNR</text>
        </g>
      </svg>
    );
  }
  return (
    <svg className="visual-svg" viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice">
      <g stroke="rgba(255,180,80,.45)" fill="none" strokeWidth="1.2">
        <path d="M 60 240 L 140 180 L 220 200 L 300 100 L 360 60" />
        <circle cx="60" cy="240" r="4" fill="rgba(255,180,80,.6)" />
        <circle cx="140" cy="180" r="4" fill="rgba(255,180,80,.6)" />
        <circle cx="220" cy="200" r="4" fill="rgba(255,180,80,.6)" />
        <circle cx="300" cy="100" r="4" fill="rgba(255,180,80,.6)" />
        <circle cx="360" cy="60" r="6" fill="rgba(255,180,80,.9)" />
        <text x="60" y="50" fill="rgba(255,180,80,.6)" fontSize="14" fontFamily="JetBrains Mono">growth ↗</text>
      </g>
    </svg>
  );
}

function Projects({ t, lang, onOpen }) {
  const [secRef, secIn] = window.PortfolioPart1.useReveal();
  return (
    <section id="work" ref={secRef}>
      <div className={`section-tag reveal ${secIn ? 'in' : ''}`}>{t.projects.tag}</div>
      <h2 className={`section-title reveal d1 ${secIn ? 'in' : ''}`}>
        {t.projects.title.map((seg, i) => typeof seg === 'string' ? <span key={i}>{seg}</span> : seg)}
      </h2>
      <p className={`reveal d2 ${secIn ? 'in' : ''}`} style={{ color: 'var(--fg-dim)', marginTop: '-40px', marginBottom: '40px', fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>
        {t.projects.sub}
      </p>

      <div className="projects-grid">
        {PROJECTS.map((p, i) => (
          <div
            key={p.id}
            className={`project-card p${i+1} reveal d${(i % 3) + 1} ${secIn ? 'in' : ''}`}
            onClick={() => onOpen(p.id)}
          >
            <div className="visual"><ProjectVisual id={p.id} /></div>
            <div className="arrow">↗</div>
            <div className="meta">
              <div className="num">
                <span>{p.num} / {String(PROJECTS.length).padStart(2,'0')}</span>
                <span className="cat">{p.cat}</span>
              </div>
              <div className="name">{p.name}</div>
              <div className="desc">{p.short[lang]}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─── Case study ─── */
function CaseStudy({ id, lang, t, onClose }) {
  const p = PROJECTS.find(x => x.id === id);
  useEffect2(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (id) {
      document.body.style.overflow = 'hidden';
      window.addEventListener('keydown', onKey);
    }
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [id, onClose]);

  if (!p) return <div className="case-study" />;

  return (
    <div className={`case-study ${id ? 'open' : ''}`}>
      <div className="case-head">
        <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--fg-dim)' }}>
          case_study / <span style={{ color: 'var(--accent)' }}>{p.id}</span>.md
        </div>
        <button className="case-close" onClick={onClose} aria-label={t.projects.cs.close}>×</button>
      </div>
      <div className="case-body">
        <div className="case-num">{p.num} / {p.cat.toUpperCase()}</div>
        <h1 className="case-title" style={{ color: p.color[lang] }}>{p.name}</h1>
        <p className="case-summary">{p.short[lang]}</p>

        <div className="case-info">
          <div>
            <div className="k">{t.projects.cs.role}</div>
            <div className="v">{p.role[lang]}</div>
          </div>
          <div>
            <div className="k">{t.projects.cs.year}</div>
            <div className="v">{p.year}</div>
          </div>
          <div>
            <div className="k">{t.projects.cs.client}</div>
            <div className="v">{p.client}</div>
          </div>
          <div>
            <div className="k">{t.projects.cs.stack}</div>
            <div className="v stack">{p.stack.join(' · ')}</div>
          </div>
        </div>

        <div className="case-mock" style={{
          background: `radial-gradient(ellipse at center, ${p.color[lang]}22, transparent 70%), #0a0d12`,
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <div style={{ width: '85%', height: '80%', position: 'relative' }}>
            <ProjectVisual id={p.id} />
            <div style={{
              position: 'absolute', top: 16, left: 16,
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: 'var(--fg-mute)', textTransform: 'uppercase', letterSpacing: '.15em'
            }}>
              [ {lang === 'pt' ? 'preview do projeto' : 'project preview'} ]
            </div>
          </div>
        </div>

        <div className="case-section">
          <h3>{t.projects.cs.overview}</h3>
          <p>{p.overview[lang]}</p>
        </div>

        <div className="case-section">
          <h3>{t.projects.cs.challenge}</h3>
          <p>{p.challenge[lang]}</p>
        </div>

        <div className="case-section">
          <h3>{t.projects.cs.solution}</h3>
          <p>{p.solution[lang]}</p>
        </div>

        <div className="case-section">
          <h3>{t.projects.cs.impact}</h3>
          <div className="case-impact">
            {p.impact.map((it, i) => (
              <div className="impact-card" key={i}>
                <div className="num" style={{ color: p.color[lang] }}>{it.num}</div>
                <div className="lbl">{it.lbl[lang]}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.PortfolioPart2 = { Skills, Projects, CaseStudy };
