"use client";

import Image from "next/image";
import dynamic from "next/dynamic";
import Link from "next/link";
import {
  ArrowDown, ArrowUpRight, BriefcaseBusiness, Code2, Download, GitBranch,
  GraduationCap, Mail, MapPin, Menu, MessageCircle, Trophy, X,
} from "lucide-react";
import { CSSProperties, ReactNode, useEffect, useRef, useState } from "react";
import type { Locale, PortfolioCopy } from "../portfolio-content";

const DraggableLanyard = dynamic(() => import("./draggable-lanyard"), {
  ssr: false,
  loading: () => <div className="lanyard-loading" aria-hidden="true"><span /></div>,
});

type PortfolioProps = { locale: Locale; copy: PortfolioCopy };

function GhostFibers() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const context = canvas.getContext("2d");
    if (!context) return;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    let width = 0;
    let height = 0;
    let frame = 0;
    let animation = 0;
    let pointerX = 0.5;
    let pointerY = 0.45;

    const resize = () => {
      const box = canvas.getBoundingClientRect();
      const ratio = Math.min(window.devicePixelRatio || 1, 1.5);
      width = box.width;
      height = box.height;
      canvas.width = Math.max(1, Math.floor(width * ratio));
      canvas.height = Math.max(1, Math.floor(height * ratio));
      context.setTransform(ratio, 0, 0, ratio, 0, 0);
    };

    const draw = () => {
      context.clearRect(0, 0, width, height);
      const gradient = context.createRadialGradient(
        width * pointerX, height * pointerY, 0,
        width * pointerX, height * pointerY, width * 0.62,
      );
      gradient.addColorStop(0, "rgba(94, 234, 212, .12)");
      gradient.addColorStop(0.46, "rgba(163, 230, 53, .04)");
      gradient.addColorStop(1, "rgba(3, 7, 18, 0)");
      context.fillStyle = gradient;
      context.fillRect(0, 0, width, height);

      for (let index = 0; index < 26; index += 1) {
        const base = (index / 25) * width;
        context.beginPath();
        for (let y = -40; y <= height + 40; y += 12) {
          const wave = Math.sin(y * 0.012 + index * 0.53 + frame * 0.006) * (18 + (index % 4) * 3);
          const ghost = Math.cos(y * 0.006 - frame * 0.003 + index) * 9;
          const pull = (pointerX - 0.5) * 30 * Math.sin((y / Math.max(height, 1)) * Math.PI);
          const x = base + wave + ghost + pull;
          if (y === -40) context.moveTo(x, y);
          else context.lineTo(x, y);
        }
        context.strokeStyle = index % 4 === 0 ? "rgba(190, 242, 100, .12)" : "rgba(103, 232, 249, .10)";
        context.lineWidth = index % 5 === 0 ? 1.2 : 0.6;
        context.stroke();
      }
      frame += 1;
      if (!reduced) animation = requestAnimationFrame(draw);
    };

    const onPointer = (event: PointerEvent) => {
      pointerX = event.clientX / Math.max(window.innerWidth, 1);
      pointerY = event.clientY / Math.max(window.innerHeight, 1);
    };

    resize();
    draw();
    window.addEventListener("resize", resize);
    window.addEventListener("pointermove", onPointer, { passive: true });
    return () => {
      cancelAnimationFrame(animation);
      window.removeEventListener("resize", resize);
      window.removeEventListener("pointermove", onPointer);
    };
  }, []);

  return <canvas ref={canvasRef} className="ghost-fibers" aria-hidden="true" />;
}

function RotatingText({ words }: { words: readonly string[] }) {
  const [index, setIndex] = useState(0);
  useEffect(() => {
    const timer = window.setInterval(() => setIndex((current) => (current + 1) % words.length), 2600);
    return () => window.clearInterval(timer);
  }, [words.length]);

  return <span className="rotating-text" aria-live="polite"><span key={words[index]}>{words[index]}</span></span>;
}

function SplitText({ children, className = "" }: { children: string; className?: string }) {
  return (
    <span className={`split-text ${className}`} aria-label={children}>
      {Array.from(children).map((letter, index) => (
        <span key={`${letter}-${index}`} aria-hidden="true" style={{ "--i": index } as CSSProperties}>
          {letter === " " ? "\u00a0" : letter}
        </span>
      ))}
    </span>
  );
}

function Reveal({ children, className = "" }: { children: ReactNode; className?: string }) {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    const observer = new IntersectionObserver(([entry]) => entry.isIntersecting && setVisible(true), { threshold: 0.14 });
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  return <div ref={ref} className={`reveal ${visible ? "is-visible" : ""} ${className}`}>{children}</div>;
}

function CircularText() {
  const text = "FATHOR ROZI • FULL STACK • ";
  return (
    <div className="circular-text" aria-hidden="true">
      {Array.from(text).map((letter, index) => (
        <span key={index} style={{ transform: `rotate(${index * (360 / text.length)}deg)` }}>{letter}</span>
      ))}
      <Code2 size={22} />
    </div>
  );
}

function SpotlightCard({ children, accent }: { children: ReactNode; accent: string }) {
  const ref = useRef<HTMLElement>(null);
  const onMove = (event: React.PointerEvent<HTMLElement>) => {
    const box = event.currentTarget.getBoundingClientRect();
    event.currentTarget.style.setProperty("--spot-x", `${event.clientX - box.left}px`);
    event.currentTarget.style.setProperty("--spot-y", `${event.clientY - box.top}px`);
  };
  return <article ref={ref} onPointerMove={onMove} className={`project-card accent-${accent}`}>{children}</article>;
}

function LanguageSwitch({ locale }: { locale: Locale }) {
  return (
    <div className="language-switch" aria-label="Language switcher">
      <Link href="/id" className={locale === "id" ? "active" : ""} aria-label="Bahasa Indonesia"><span aria-hidden="true">🇮🇩</span><b>ID</b></Link>
      <Link href="/en" className={locale === "en" ? "active" : ""} aria-label="English"><span aria-hidden="true">🇬🇧</span><b>EN</b></Link>
    </div>
  );
}

function Header({ locale, copy }: PortfolioProps) {
  const [open, setOpen] = useState(false);
  return (
    <header className="site-header">
      <Link className="brand" href={`/${locale}`} aria-label="Fathor Rozi home"><span>FR</span><i /></Link>
      <nav className="desktop-nav" aria-label={copy.menuLabel}>
        {copy.nav.map(([label, id]) => <a href={`#${id}`} key={id}>{label}</a>)}
      </nav>
      <div className="header-actions">
        <LanguageSwitch locale={locale} />
        <button className="menu-button" onClick={() => setOpen(!open)} aria-label={copy.menuLabel} aria-expanded={open}>{open ? <X size={20} /> : <Menu size={20} />}</button>
      </div>
      {open && (
        <nav className="mobile-menu" aria-label={copy.menuLabel}>
          {copy.nav.map(([label, id], index) => <a href={`#${id}`} key={id} onClick={() => setOpen(false)}><span>0{index + 1}</span>{label}</a>)}
        </nav>
      )}
    </header>
  );
}

export default function Portfolio({ locale, copy }: PortfolioProps) {
  useEffect(() => { document.documentElement.lang = locale; }, [locale]);

  return (
    <main className="portfolio-shell">
      <Header locale={locale} copy={copy} />
      <section className="hero" id="home">
        <GhostFibers />
        <div className="hero-grid page-width">
          <div className="hero-copy">
            <div className="availability"><i />{copy.availability}</div>
            <p className="hero-greeting">{copy.greeting}</p>
            <h1><SplitText>{copy.firstName}</SplitText><br /><SplitText className="outline-name">{copy.lastName}</SplitText></h1>
            <div className="role-line"><span>→</span><RotatingText words={copy.roles} /></div>
            <p className="hero-summary">{copy.summary}</p>
            <div className="hero-actions">
              <a className="button button-primary" href="#contact">{copy.contactCta}<ArrowUpRight size={18} /></a>
              <a className="button button-ghost" href="#projects">{copy.projectsCta}<ArrowDown size={18} /></a>
              <a className="text-link" href={copy.cvHref} download><Download size={17} />{copy.cvCta}</a>
            </div>
          </div>
          <div className="hero-visual">
            <div className="drag-hint"><span />{locale === "id" ? "Tarik kartu" : "Drag the card"}</div>
            <DraggableLanyard role={copy.roles[0]} />
            <CircularText />
          </div>
        </div>
        <a className="scroll-cue" href="#about" aria-label={copy.aboutEyebrow}><span>SCROLL</span><ArrowDown size={16} /></a>
      </section>

      <div className="velocity-strip" aria-hidden="true"><div><span>{copy.scrollText}</span><span>{copy.scrollText}</span></div></div>

      <section className="section about-section page-width" id="about">
        <Reveal className="section-heading"><p className="eyebrow">{copy.aboutEyebrow}</p><h2>{copy.aboutTitle}</h2></Reveal>
        <div className="about-grid">
          <Reveal className="about-story">
            {copy.aboutBody.map((paragraph) => <p key={paragraph}>{paragraph}</p>)}
            <div className="about-links"><a href={`mailto:${copy.email}`}><Mail size={17} />{copy.email}</a><a href={copy.githubUrl} target="_blank" rel="noreferrer"><GitBranch size={17} />{copy.github}</a></div>
          </Reveal>
          <Reveal className="stats-grid">{copy.stats.map(([number, label]) => <div className="stat-card" key={label}><strong>{number}</strong><span>{label}</span></div>)}</Reveal>
          <Reveal className="identity-card">
            <div className="identity-photo"><Image src="/assets/fathorrozi.jpg" alt="Fathor Rozi" fill sizes="(max-width: 768px) 90vw, 420px" /></div>
            <div className="identity-details"><span className="micro-label">{copy.identityTitle}</span>{copy.identities.map(([label, value]) => <div key={label}><small>{label}</small><p>{value}</p></div>)}</div>
          </Reveal>
        </div>
      </section>

      <section className="section journey-section" id="experience"><div className="page-width">
        <Reveal className="section-heading split-heading"><div><p className="eyebrow">{copy.experienceEyebrow}</p><h2>{copy.experienceTitle}</h2></div><p>{copy.experienceIntro}</p></Reveal>
        <div className="journey-grid">
          <div className="timeline">{copy.experiences.map((item, index) => (
            <Reveal className={`timeline-item ${"featured" in item && item.featured ? "featured" : ""}`} key={`${item.company}-${item.year}`}>
              <div className="timeline-marker"><span>{String(index + 1).padStart(2, "0")}</span></div>
              <div className="timeline-copy"><p className="timeline-year">{item.year}</p><h3>{item.company}</h3><h4>{item.role}</h4><ul>{item.points.map((point) => <li key={point}>{point}</li>)}</ul></div>
            </Reveal>
          ))}</div>
          <aside className="education-panel">
            <div className="panel-icon"><GraduationCap /></div><h3>{copy.educationTitle}</h3>
            {copy.education.map(([year, school, program]) => <div className="education-item" key={school}><span>{year}</span><strong>{school}</strong><p>{program}</p></div>)}
          </aside>
        </div>
      </div></section>

      <section className="section projects-section page-width" id="projects">
        <Reveal className="section-heading split-heading"><div><p className="eyebrow">{copy.projectsEyebrow}</p><h2>{copy.projectsTitle}</h2></div><p>{copy.projectsIntro}</p></Reveal>
        <div className="projects-grid">{copy.projects.map((project) => (
          <Reveal key={project.title}><SpotlightCard accent={project.accent}>
            <div className="project-top"><span>{project.number}</span><ArrowUpRight /></div>
            <div className="project-orbit" aria-hidden="true"><i /><i /><Code2 /></div>
            <div className="project-content"><p>{project.subtitle}</p><h3>{project.title}</h3><span>{project.description}</span><div className="tags">{project.tags.map((tag) => <b key={tag}>{tag}</b>)}</div><a href={project.href} target="_blank" rel="noreferrer">{copy.visit}<ArrowUpRight size={17} /></a></div>
          </SpotlightCard></Reveal>
        ))}</div>
      </section>

      <div className="tool-loop" aria-label={copy.tools.join(", ")}><div>{[...copy.tools, ...copy.tools].map((tool, index) => <span key={`${tool}-${index}`}><i />{tool}</span>)}</div></div>

      <section className="section skills-section page-width" id="skills">
        <Reveal className="section-heading"><p className="eyebrow">{copy.skillsEyebrow}</p><h2>{copy.skillsTitle}</h2></Reveal>
        <div className="skills-layout">
          <Reveal className="skill-panel"><div className="panel-title"><Code2 /><h3>{copy.technicalTitle}</h3></div><div className="skill-list">
            {copy.skills.map(([skill, level]) => <div className="skill-row" key={skill}><div><span>{skill}</span><b>{level}%</b></div><i><span style={{ "--level": `${level}%` } as CSSProperties} /></i></div>)}
          </div></Reveal>
          <div className="right-panels">
            <Reveal className="soft-panel"><div className="panel-title"><BriefcaseBusiness /><h3>{copy.softTitle}</h3></div><div className="soft-cloud">{copy.softSkills.map((skill, index) => <span key={skill} style={{ "--delay": `${index * 90}ms` } as CSSProperties}>{skill}</span>)}</div></Reveal>
            <Reveal className="awards-panel"><div className="panel-title"><Trophy /><h3>{copy.awardsTitle}</h3></div>{copy.awards.map(([title, event, meta]) => <div className="award" key={event}><strong>{title}</strong><div><b>{event}</b><span>{meta}</span></div></div>)}</Reveal>
          </div>
        </div>
      </section>

      <section className="contact-section" id="contact"><GhostFibers /><div className="page-width contact-inner">
        <Reveal><p className="eyebrow">{copy.contactEyebrow}</p><h2>{copy.contactTitle}</h2><p className="contact-body">{copy.contactBody}</p></Reveal>
        <Reveal className="contact-actions">
          <a href={`mailto:${copy.email}`}><span><Mail /></span><div><small>{copy.emailLabel}</small><strong>{copy.email}</strong></div><ArrowUpRight /></a>
          <a href={copy.whatsappUrl} target="_blank" rel="noreferrer"><span><MessageCircle /></span><div><small>{copy.whatsappLabel}</small><strong>{copy.phone}</strong></div><ArrowUpRight /></a>
          <a href={copy.githubUrl} target="_blank" rel="noreferrer"><span><GitBranch /></span><div><small>{copy.githubLabel}</small><strong>{copy.github}</strong></div><ArrowUpRight /></a>
        </Reveal>
        <div className="contact-bottom"><a className="button button-primary" href={copy.cvHref} download><Download size={18} />{copy.cvCta}</a><p><MapPin size={16} />Sumenep, East Java, Indonesia</p></div>
      </div></section>

      <footer><div className="page-width"><Link href={`/${locale}`}>FR<span>.</span></Link><p>{copy.footer}</p><span>© {new Date().getFullYear()}</span></div></footer>
    </main>
  );
}
