// Projects, Testimonials, FAQ, CTA, Footer
const { useState: useS3, useEffect: useE3 } = React;

function ProjectVisual({ variant, accent }) {
  // Abstract placeholder visuals per project
  const visuals = {
    dashboard: (
      <svg viewBox="0 0 400 300" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ background: 'var(--bg-tint)' }}>
        <defs>
          <linearGradient id="pg1" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0" stopColor="#7C5CFF" stopOpacity="0.2"/>
            <stop offset="1" stopColor="#7C5CFF" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <rect x="30" y="30" width="340" height="240" rx="10" fill="var(--bg-elev)" stroke="var(--line)"/>
        <rect x="50" y="50" width="80" height="10" rx="3" fill="var(--fg-faint)"/>
        <rect x="50" y="75" width="120" height="28" rx="4" fill="var(--fg)"/>
        <rect x="50" y="125" width="300" height="120" rx="6" fill="url(#pg1)"/>
        <path d="M50 220 Q 120 180 200 200 T 350 150" stroke="#7C5CFF" strokeWidth="2" fill="none"/>
        <circle cx="200" cy="200" r="4" fill="#7C5CFF"/>
        <rect x="290" y="50" width="60" height="20" rx="10" fill="#7C5CFF"/>
      </svg>
    ),
    system: (
      <svg viewBox="0 0 400 300" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ background: 'var(--bg-tint)' }}>
        <g>
          {Array.from({ length: 6 }).map((_, i) => (
            Array.from({ length: 8 }).map((_, j) => (
              <rect key={`${i}-${j}`} x={30 + j * 45} y={30 + i * 45} width="35" height="35" rx="6"
                fill={(i + j) % 5 === 0 ? '#7C5CFF' : 'var(--bg-elev)'} stroke="var(--line)" />
            ))
          ))}
        </g>
      </svg>
    ),
    launch: (
      <svg viewBox="0 0 400 300" width="100%" height="100%" preserveAspectRatio="xMidYMid slice">
        <defs>
          <radialGradient id="pg2" cx="0.5" cy="0.5" r="0.6">
            <stop offset="0" stopColor="#7C5CFF" stopOpacity="0.6"/>
            <stop offset="1" stopColor="#7C5CFF" stopOpacity="0"/>
          </radialGradient>
        </defs>
        <rect width="400" height="300" fill="var(--bg-tint)"/>
        <circle cx="200" cy="150" r="140" fill="url(#pg2)"/>
        <text x="200" y="155" textAnchor="middle" fontSize="64" fill="var(--fg)" fontFamily="serif" fontStyle="italic" fontWeight="400">launch</text>
        <rect x="150" y="200" width="100" height="3" fill="#7C5CFF"/>
      </svg>
    ),
    workflow: (
      <svg viewBox="0 0 400 300" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ background: 'var(--bg-tint)' }}>
        <g>
          <rect x="40" y="50" width="100" height="60" rx="8" fill="var(--bg-elev)" stroke="var(--line)"/>
          <rect x="150" y="120" width="100" height="60" rx="8" fill="#7C5CFF" opacity="0.2"/>
          <rect x="150" y="120" width="100" height="60" rx="8" fill="none" stroke="#7C5CFF"/>
          <rect x="260" y="190" width="100" height="60" rx="8" fill="var(--bg-elev)" stroke="var(--line)"/>
          <path d="M140 80 L 150 120 M250 150 L 260 190" stroke="var(--fg-faint)" strokeDasharray="3 3"/>
          <circle cx="90" cy="80" r="4" fill="#7C5CFF"/>
          <circle cx="200" cy="150" r="4" fill="#7C5CFF"/>
          <circle cx="310" cy="220" r="4" fill="#7C5CFF"/>
        </g>
      </svg>
    ),
    studio: (
      <svg viewBox="0 0 400 300" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ background: 'var(--bg-tint)' }}>
        <rect width="400" height="300" fill="var(--bg-tint)"/>
        <g fontFamily="serif" fontStyle="italic" fill="var(--fg)">
          <text x="30" y="130" fontSize="90" fontWeight="400">studio</text>
          <text x="30" y="195" fontSize="16" opacity="0.6" fontFamily="sans-serif" fontStyle="normal">portfolio · 2024</text>
        </g>
        <circle cx="350" cy="50" r="20" fill="#7C5CFF"/>
      </svg>
    )
  };
  return visuals[variant] || visuals.dashboard;
}

function ProjectModal({ project, variant, onClose, t }) {
  // Keep onClose in a ref so the scroll-lock effect only reacts to `project`
  // (otherwise every parent re-render creates a new onClose fn and retriggers
  // this effect, which can leave body.overflow stuck at "hidden").
  const onCloseRef = React.useRef(onClose);
  React.useEffect(() => { onCloseRef.current = onClose; }, [onClose]);

  useE3(() => {
    if (!project) return;
    function onKey(e) { if (e.key === 'Escape') onCloseRef.current(); }
    document.body.style.overflow = 'hidden';
    document.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      document.removeEventListener('keydown', onKey);
    };
  }, [project]);

  // Extra safety net: if this component ever unmounts mid-open, restore scroll.
  useE3(() => () => { document.body.style.overflow = ''; }, []);

  if (!project) return null;

  const description = project.description || t.projects.soon_desc;
  const hasImage = Boolean(project.image);
  const hasTech = Array.isArray(project.tech) && project.tech.length > 0;
  const hasUrl = Boolean(project.url);

  return (
    <div className="project-modal-backdrop" onClick={onClose} role="dialog" aria-modal="true">
      <div className="project-modal" onClick={(e) => e.stopPropagation()}>
        <button className="project-modal-close" onClick={onClose} aria-label={t.projects.close}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M3 3L13 13M13 3L3 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
        <div className="project-modal-image">
          {hasImage
            ? <img src={project.image} alt={project.name} />
            : <ProjectVisual variant={variant} />
          }
        </div>
        <div className="project-modal-content">
          <div className="project-modal-meta">
            <span>{project.tag}</span>
            <span>{project.year}</span>
          </div>
          <h3 className="project-modal-title">{project.name}</h3>
          <p className="project-modal-desc">{description}</p>
          {hasTech && (
            <div className="project-modal-tech-group">
              <span className="project-modal-tech-label">{t.projects.tech_label}</span>
              <div className="project-modal-tech">
                {project.tech.map((tag) => (
                  <span key={tag} className="tag">{tag}</span>
                ))}
              </div>
            </div>
          )}
          {hasUrl && (
            <a
              href={project.url}
              target="_blank"
              rel="noopener noreferrer"
              className="btn btn-primary project-modal-live"
            >
              {t.projects.live_cta}
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
            </a>
          )}
        </div>
      </div>
    </div>
  );
}

function Projects({ t }) {
  const variants = ['dashboard', 'system', 'launch', 'workflow', 'studio'];
  const layouts = ['project-large', 'project-small', 'project-full', 'project-half', 'project-half'];
  const [activeIdx, setActiveIdx] = useS3(null);

  // Hover parallax
  useE3(() => {
    const cards = document.querySelectorAll('.project');
    function onMove(e) {
      const rect = e.currentTarget.getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width - 0.5;
      const y = (e.clientY - rect.top) / rect.height - 0.5;
      const vis = e.currentTarget.querySelector('.project-visual');
      if (vis) vis.style.transform = `translate(${x * 20}px, ${y * 20}px) scale(1.05)`;
    }
    function onLeave(e) {
      const vis = e.currentTarget.querySelector('.project-visual');
      if (vis) vis.style.transform = '';
    }
    cards.forEach(c => {
      c.addEventListener('mousemove', onMove);
      c.addEventListener('mouseleave', onLeave);
    });
    return () => cards.forEach(c => {
      c.removeEventListener('mousemove', onMove);
      c.removeEventListener('mouseleave', onLeave);
    });
  }, []);

  const activeProject = activeIdx !== null ? t.projects.items[activeIdx] : null;
  const activeVariant = activeIdx !== null ? variants[activeIdx] : null;

  return (
    <section id="projects">
      <div className="container">
        <SectionHeader num={t.projects.num} label={t.projects.label} title={t.projects.title} titleEm={t.projects.titleEm} subtitle={t.projects.subtitle} />
        <div className="projects-grid">
          {t.projects.items.map((p, i) => (
            <a
              key={i}
              href="#"
              onClick={(e) => { e.preventDefault(); setActiveIdx(i); }}
              className={`project reveal ${layouts[i]}`}
              style={{ '--d': `${i * 60}ms` }}
            >
              <div className="project-visual" style={{ transition: 'transform 0.6s var(--ease-out)' }}>
                {p.image
                  ? <img src={p.image} alt={p.name} className="project-image" />
                  : <ProjectVisual variant={variants[i]} />
                }
              </div>
              <div className="project-content">
                <div className="project-top">
                  <span className="project-tag">{p.tag}</span>
                  <span className="project-year">{p.year}</span>
                </div>
                <div className="project-bottom">
                  <h3 className="project-name">{p.name}<br/><em>{t.projects.soon}</em></h3>
                  <div className="project-arrow">
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                      <path d="M4 12L12 4M12 4H6M12 4V10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                    </svg>
                  </div>
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
      <ProjectModal
        project={activeProject}
        variant={activeVariant}
        onClose={() => setActiveIdx(null)}
        t={t}
      />
    </section>
  );
}

function Testimonials({ t }) {
  return (
    <section id="testimonials">
      <div className="container">
        <SectionHeader num={t.testimonials.num} label={t.testimonials.label} title={t.testimonials.title} titleEm={t.testimonials.titleEm} />
        <div className="testimonials-grid">
          {t.testimonials.items.map((item, i) => (
            <div key={i} className="testimonial reveal" style={{ '--d': `${i * 80}ms` }}>
              <svg width="28" height="28" viewBox="0 0 28 28" fill="none" style={{ color: 'var(--accent)', opacity: 0.8 }}>
                <path d="M10 8C7 8 5 10 5 13v7h7v-7H8c0-2 1-3 2-3V8zM22 8c-3 0-5 2-5 5v7h7v-7h-4c0-2 1-3 2-3V8z" fill="currentColor"/>
              </svg>
              <div className="testimonial-quote">{item.quote}</div>
              <div className="testimonial-author">
                <div className="testimonial-avatar">{item.initials}</div>
                <div className="testimonial-meta">
                  <div className="testimonial-name">{item.name}</div>
                  <div className="testimonial-role">{item.role}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FAQ({ t }) {
  const [open, setOpen] = useS3(0);
  return (
    <section id="faq">
      <div className="container">
        <SectionHeader num={t.faq.num} label={t.faq.label} title={t.faq.title} titleEm={t.faq.titleEm} />
        <div className="faq-list reveal">
          {t.faq.items.map((item, i) => (
            <div key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{item.q}</span>
                <span className="faq-icon">+</span>
              </button>
              <div className="faq-a">
                <div className="faq-a-inner">{item.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function CTA({ t }) {
  const canvasRef = React.useRef(null);
  useE3(() => {
    const c = canvasRef.current;
    if (!c) return;
    const ctx = c.getContext('2d');
    let W, H;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    function resize() {
      const rect = c.getBoundingClientRect();
      W = rect.width; H = rect.height;
      c.width = Math.max(1, Math.round(W * dpr));
      c.height = Math.max(1, Math.round(H * dpr));
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(c);
    window.addEventListener('resize', resize);
    let t0 = performance.now();
    let raf;
    // Orbs pushed FAR off-screen (|x|, |y| ~ 0.4–1.5) so only the smooth
    // tails of the gradient are visible → no hot spots, no visible edges.
    const orbs = [
      { x: -0.40, y: 0.20, r: 1.6, hue: 262, speed: 0.00022, phase: 0.0 },
      { x:  1.40, y: 0.45, r: 1.5, hue: 272, speed: 0.00026, phase: 2.3 },
      { x:  0.55, y: 1.55, r: 1.7, hue: 258, speed: 0.00020, phase: 4.1 },
      { x:  0.35, y: -0.45, r: 1.4, hue: 268, speed: 0.00024, phase: 1.2 },
      { x:  0.90, y: -0.30, r: 1.3, hue: 275, speed: 0.00028, phase: 3.5 },
    ];
    function draw() {
      const dark = document.documentElement.getAttribute('data-theme') === 'dark';
      ctx.fillStyle = dark ? '#0A0A0C' : '#FAFAFA';
      ctx.fillRect(0, 0, W, H);
      const tt = (performance.now() - t0);
      for (const o of orbs) {
        const px = (o.x + Math.sin(tt * o.speed + o.phase) * 0.04) * W;
        const py = (o.y + Math.cos(tt * o.speed * 1.2 + o.phase) * 0.035) * H;
        const r = o.r * Math.max(W, H);
        const g = ctx.createRadialGradient(px, py, 0, px, py, r);
        const alpha = dark ? 0.32 : 0.16;
        // Smoother 5-stop falloff → orbs blend into a uniform mesh
        g.addColorStop(0.00, `hsla(${o.hue}, 78%, 72%, ${alpha})`);
        g.addColorStop(0.25, `hsla(${o.hue}, 78%, 72%, ${alpha * 0.75})`);
        g.addColorStop(0.50, `hsla(${o.hue}, 78%, 72%, ${alpha * 0.42})`);
        g.addColorStop(0.75, `hsla(${o.hue}, 78%, 72%, ${alpha * 0.16})`);
        g.addColorStop(1.00, `hsla(${o.hue}, 78%, 72%, 0)`);
        ctx.fillStyle = g;
        ctx.fillRect(0, 0, W, H);
      }
      raf = requestAnimationFrame(draw);
    }
    draw();
    return () => { cancelAnimationFrame(raf); ro.disconnect(); window.removeEventListener('resize', resize); };
  }, []);
  return (
    <section id="contact" className="cta">
      <canvas ref={canvasRef} className="cta-bg"></canvas>
      <div className="container cta-inner">
        <span className="eyebrow reveal">[ {t.cta.num} ] · {t.cta.label}</span>
        <h2 className="cta-title reveal" style={{ '--d': '100ms' }}>
          {t.cta.title1}<br/>
          <em>{t.cta.title2}</em><br/>
          {t.cta.title3}
        </h2>
        <p className="cta-subtitle reveal" style={{ '--d': '200ms' }}>{t.cta.subtitle}</p>
        <a href={`mailto:${t.cta.email}`} className="cta-email magnetic reveal" data-magnetic style={{ '--d': '300ms' }}>
          {t.cta.email}
          <svg className="cta-email-arrow" width="18" height="18" viewBox="0 0 18 18" fill="none">
            <path d="M4 14L14 4M14 4H7M14 4V11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </a>
        <a
          href={`https://wa.me/${t.cta.whatsapp_raw}`}
          target="_blank"
          rel="noopener noreferrer"
          className="cta-whatsapp reveal"
          style={{ '--d': '400ms' }}
        >
          <span className="cta-whatsapp-dot"></span>
          <span>{t.cta.whatsapp_label} · {t.cta.whatsapp_display}</span>
        </a>
      </div>
    </section>
  );
}

function Footer({ t }) {
  return (
    <footer>
      <div className="container">
        <div className="footer-top">
          <h2 className="footer-big reveal">
            {t.footer.big1} <em>{t.footer.big2}</em><br/>
            {t.footer.big3}
          </h2>
          <div className="footer-right reveal" style={{ '--d': '150ms' }}>
            <span className="footer-contact-label">{t.footer.contact_label}</span>
            <a href={`mailto:${t.cta.email}`} className="footer-contact-email">
              {t.cta.email}
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
              </svg>
            </a>
            <a
              href={`https://wa.me/${t.cta.whatsapp_raw}`}
              target="_blank"
              rel="noopener noreferrer"
              className="footer-contact-whatsapp"
            >
              <span className="cta-whatsapp-dot"></span>
              <span>{t.cta.whatsapp_display}</span>
            </a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.copyright}</span>
          <span>{t.footer.role}</span>
          <span>{t.footer.location}</span>
          <span>{t.footer.builtwith}</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Projects, Testimonials, FAQ, CTA, Footer });
