const { useState, useEffect } = React;

function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  el.scrollIntoView({ behavior: "smooth", block: "start" });
}

function useReveal() {
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add("is-visible");
            observer.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.18 }
    );

    const targets = document.querySelectorAll("[data-animate]");
    targets.forEach((target) => observer.observe(target));

    return () => observer.disconnect();
  }, []);
}

function useTypewriter(text, speed = 50) {
  const [displayedText, setDisplayedText] = useState("");
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (currentIndex < text.length) {
      const timeout = setTimeout(() => {
        setDisplayedText((prev) => prev + text[currentIndex]);
        setCurrentIndex((prev) => prev + 1);
      }, speed);

      return () => clearTimeout(timeout);
    }
  }, [currentIndex, text, speed]);

  useEffect(() => {
    setDisplayedText("");
    setCurrentIndex(0);
  }, [text]);

  return displayedText;
}

function Navbar() {
  const [open, setOpen] = useState(false);
  const sections = [
    { id: "hero", label: "Home" },
    { id: "about", label: "Profile" },
    { id: "stack", label: "Stack" },
    { id: "skills", label: "Capabilities" },
    { id: "projects", label: "Projects" },
    { id: "experience", label: "Experience" },
    { id: "contact", label: "Contact" },
  ];

  const navigate = (id) => {
    scrollToId(id);
    setOpen(false);
  };

  return (
    <header className='nav-shell'>
      <div className='container nav-inner'>
        <button className='nav-brand' onClick={() => navigate("hero")}>
          <div className='nav-glyph'>
            <img src='assets/adam.jpeg' alt='Adam Arbai' />
          </div>
          <div>
            <span className='nav-title'>Adam Arbai</span>
            <p className='nav-subtitle'>Data Scientist</p>
          </div>
        </button>

        <nav className={`nav-menu ${open ? "is-open" : ""}`}>
          {sections.map((section) => (
            <button
              key={section.id}
              className='nav-link'
              onClick={() => navigate(section.id)}>
              {section.label}
            </button>
          ))}
          <button
            className='nav-link nav-link-primary'
            onClick={() => navigate("contact")}>
            Get in touch
          </button>
        </nav>

        <button
          className={`nav-toggle ${open ? "is-open" : ""}`}
          aria-label='Toggle navigation'
          onClick={() => setOpen((prev) => !prev)}>
          <span />
          <span />
          <span />
        </button>
      </div>
    </header>
  );
}

function SectionHeader({ eyebrow, title, subtitle, align = "left" }) {
  return (
    <div className={`section-header ${align === "center" ? "is-center" : ""}`}>
      <p className='section-eyebrow'>{eyebrow}</p>
      <h2 className='section-title'>{title}</h2>
      {subtitle && <p className='section-subtitle'>{subtitle}</p>}
    </div>
  );
}

function SignalTicker() {
  const signals = [
    { metric: "35%", label: "variance reduced in supply forecasts" },
    { metric: "12M+", label: "rows cleaned, enriched & modeled" },
    { metric: "8", label: "end-to-end ML deployments" },
    { metric: "4", label: "industries supported to date" },
    { metric: "∞", label: "curiosity for better data stories" },
  ];

  const items = [...signals, ...signals];

  return (
    <div className='signal-ticker' aria-hidden='true'>
      <div className='signal-track'>
        {items.map((item, index) => (
          <div key={`${item.metric}-${index}`} className='signal-item'>
            <span>{item.metric}</span>
            <p>{item.label}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function Hero() {
  const fullText = "Turning raw signals into\nconfident decisions.";
  const typedText = useTypewriter(fullText, 60);
  const [showCursor, setShowCursor] = useState(true);

  useEffect(() => {
    if (typedText.length > 0) {
      const cursorInterval = setInterval(() => {
        setShowCursor((prev) => !prev);
      }, 530);
      return () => clearInterval(cursorInterval);
    }
  }, [typedText.length]);

  const stats = [
    { label: "Time-series focus", value: "LSTM · Prophet · ARIMA" },
    { label: "Stack", value: "Python · SQL · Spark" },
    { label: "Deployment", value: "MLflow · Docker · Airflow" },
    { label: "Collaboration", value: "Business-first storytelling" },
  ];

  const focus = [
    {
      title: "Forecasting systems",
      detail: "Resilient, monitored models tuned for supply & demand.",
    },
    {
      title: "Decision intelligence",
      detail: "Dashboards paired with statistical rigor for execs.",
    },
    {
      title: "Data reliability",
      detail: "Validation layers that keep pipelines trustworthy.",
    },
  ];

  const lines = typedText.split('\n');
  const firstLine = lines[0] || '';
  const secondLine = lines[1] || '';

  return (
    <section id='hero' className='section hero' data-animate>
      <div className='hero-orb hero-orb-a' />
      <div className='hero-orb hero-orb-b' />
      <div className='container hero-shell'>
        <div className='hero-intro'>
          <p className='hero-eyebrow'>Data Scientist · ML Engineer</p>
          <h1 className='hero-title'>
            {firstLine}
            {secondLine && (
              <>
                <br />
                <span>{secondLine}</span>
              </>
            )}
            {typedText.length > 0 && (
              <span className={`typewriter-cursor ${showCursor ? 'visible' : ''}`}>|</span>
            )}
          </h1>
          <p className='hero-description'>
            I design machine learning systems that stay explainable, measurable,
            and production-ready—so data leaders can trust every decision.
          </p>
          <div className='hero-actions'>
            <button
              className='button button-solid'
              onClick={() => scrollToId("projects")}>
              Explore projects
            </button>
            <button
              className='button button-ghost'
              onClick={() => scrollToId("contact")}>
              Book a call
            </button>
          </div>
          <div className='hero-focus-grid'>
            {focus.map((item) => (
              <article key={item.title} className='focus-card'>
                <h3>{item.title}</h3>
                <p>{item.detail}</p>
              </article>
            ))}
          </div>
        </div>

        <div className='hero-visual'>
          <div className='hero-core'>
            <div className='hero-core-ring' />
            <div className='hero-avatar'>
              <span>AA</span>
            </div>
            <div className='hero-satellite hero-satellite-one'>
              <p>Model drift</p>
              <span>-18%</span>
            </div>
            <div className='hero-satellite hero-satellite-two'>
              <p>Latency</p>
              <span>45 ms</span>
            </div>
          </div>
          <div className='hero-metrics'>
            <div>
              <p className='metric-label'>Confidence index</p>
              <div className='metric-bar'>
                <span style={{ width: "86%" }} />
              </div>
              <p className='metric-value'>0.86</p>
            </div>
            <div>
              <p className='metric-label'>Deployment health</p>
              <div className='metric-bar'>
                <span style={{ width: "94%" }} />
              </div>
              <p className='metric-value'>green</p>
            </div>
          </div>
        </div>
      </div>

      <div className='container hero-stats-grid'>
        {stats.map((stat) => (
          <div key={stat.label} className='stat-card'>
            <p>{stat.label}</p>
            <span>{stat.value}</span>
          </div>
        ))}
      </div>

      <SignalTicker />
    </section>
  );
}

function StackShowcase() {
  const stack = [
    {
      title: "Languages",
      caption: "Expressive, fast experimentation",
      icon: "λ",
      items: ["Python", "JS", "SQL", "C++", "Java"],
    },
    {
      title: "ML Systems",
      caption: "Training to deployment",
      icon: "Σ",
      items: [
        "PyTorch",
        "TensorFlow",
        "scikit-learn",
        "LightGBM",
        "XGBoost",
        "CatBoost",
      ],
    },
    {
      title: "Data Platform",
      caption: "Where pipelines live",
      icon: "☁",
      items: ["Spark", "Databricks", "Airflow", "dbt", "Kafka", "Dask"],
    },
    {
      title: "Visualization & BI",
      caption: "Narratives your execs keep open",
      icon: "◲",
      items: ["Plotly", "Power BI", "Tableau", "Looker", "Metabase"],
    },
    {
      title: "Storage & Ops",
      caption: "Secure, auditable data layers",
      icon: "🗄",
      items: ["PostgreSQL", "Oracle", "DB2", "MongoDB", "Snowflake"],
    },
    {
      title: "MLOps & Reliability",
      caption: "Observability and governance",
      icon: "⚙",
      items: [
        "MLflow",
        "Docker",
        "Kubernetes",
        "Great Expectations",
        "Weights & Biases",
      ],
    },
  ];

  return (
    <section id='stack' className='section' data-animate>
      <div className='container stack-shell'>
        <SectionHeader
          eyebrow='Stack'
          title='A toolchain built for analytical rigor'
          subtitle='Balanced between rapid prototypes and enterprise-ready deployments.'
        />
        <div className='stack-grid'>
          {stack.map((group) => (
            <article key={group.title} className='stack-card'>
              <div className='stack-card-top'>
                <div className='stack-icon' aria-hidden='true'>
                  {group.icon}
                </div>
                <div>
                  <h3>{group.title}</h3>
                  <p>{group.caption}</p>
                </div>
              </div>
              <div className='stack-tags'>
                {group.items.map((item) => (
                  <span key={item} className='stack-tag'>
                    {item}
                  </span>
                ))}
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function About() {
  const highlights = [
    {
      label: "Impact",
      detail: "35% variance drop across forecasting suites.",
    },
    {
      label: "Focus",
      detail: "Time-series · ML governance · Product analytics.",
    },
    {
      label: "Working style",
      detail: "Translate fuzzy questions into testable hypotheses.",
    },
  ];

  const badges = [
    "Machine Learning",
    "Time Series",
    "Data Storytelling",
    "Experimentation",
    "Product Analytics",
    "Model Governance",
  ];

  return (
    <section id='about' className='section' data-animate>
      <div className='container about-grid'>
        <article className='bio-panel'>
          <SectionHeader
            eyebrow='Profile'
            title='Data scientist with a product heartbeat'
            subtitle='I design and deploy production-grade ML and analytical systems, ensuring they deliver the consistent, high-fidelity insights that business partners depend on for daily decision-making.'
          />
          <p className='bio-paragraph'>
            Leveraging a background in econometrics and robust data warehousing,
            my focus is on data-to-outcome translation: specializing in
            connecting imperfect datasets to clear, measurable business results.
            I am equally adept at driving fast-paced experimentation and
            ensuring a disciplined, sustainable rollout of production-ready
            systems.
          </p>
          <p className='bio-paragraph'>
            My work spans forecasting demand, diagnosing churn, and designing
            experiment frameworks for cross-functional teams. I care deeply
            about interpretability, reproducibility, and UX around data so
            stakeholders can act confidently.
          </p>
          <div className='highlight-list'>
            {highlights.map((item) => (
              <div key={item.label} className='highlight-item'>
                <p>{item.label}</p>
                <span>{item.detail}</span>
              </div>
            ))}
          </div>
        </article>

        <aside className='impact-card'>
          <div className='impact-header'>
            <p>Snapshot</p>
            <span>Updated · 2025</span>
          </div>
          <div className='impact-stat'>
            <span>2+</span>
            <p>years blending science & storytelling</p>
          </div>
          <div className='impact-grid'>
            <div>
              <p>Industries</p>
              <span>Logistics,Mobility, Retail, </span>
            </div>
            <div>
              <p>Collaboration</p>
              <span>Product, Ops, Finance leaders</span>
            </div>
          </div>
          <div className='badge-cloud'>
            {badges.map((badge) => (
              <span key={badge}>{badge}</span>
            ))}
          </div>
        </aside>
      </div>
    </section>
  );
}

function Capabilities() {
  const capabilities = [
    {
      title: "Predictive intelligence",
      tag: "Forecasting · ML",
      items: [
        "Demand planning",
        "Scenario modeling",
        "AutoML pipelines",
        "Model monitoring",
      ],
    },
    {
      title: "Data platforms",
      tag: "Pipelines · Quality",
      items: [
        "ELT design",
        "Great Expectations",
        "Feature stores",
        "Data contracts",
      ],
    },
    {
      title: "Analytics storytelling",
      tag: "Activation",
      items: [
        "Executive dashboards",
        "Self-serve experiments",
        "Narrative reporting",
        "Workshop facilitation",
      ],
    },
    {
      title: "Experimentation",
      tag: "Measurement",
      items: [
        "Causal inference",
        "A/B testing",
        "Uplift modeling",
        "Metric design",
      ],
    },
  ];

  return (
    <section id='skills' className='section' data-animate>
      <div className='container'>
        <SectionHeader
          eyebrow='Capabilities'
          title='What partnerships with me feel like'
          subtitle='From exploration to scale with one consistent data partner.'
        />
        <div className='capability-grid'>
          {capabilities.map((group) => (
            <article key={group.title} className='capability-card'>
              <div className='capability-top'>
                <h3>{group.title}</h3>
                <span>{group.tag}</span>
              </div>
              <ul>
                {group.items.map((item) => (
                  <li key={item}>{item}</li>
                ))}
              </ul>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProjectCard({ project }) {
  return (
    <article className='project-card' data-animate>
      <div className='project-headline'>
        <p>{project.category}</p>
        <span>{project.metric}</span>
      </div>
      <h3>{project.title}</h3>
      <p className='project-summary'>{project.description}</p>
      <p className='project-impact'>{project.impact}</p>
      <div className='project-tags'>
        {project.tags.map((tag) => (
          <span key={tag}>{tag}</span>
        ))}
      </div>
      <div className='project-footer'>
        <span>Case study coming soon</span>
        <button className='text-link' onClick={(e) => e.preventDefault()}>
          View placeholder ↗
        </button>
      </div>
    </article>
  );
}

function Projects() {
  const projects = [
    {
      title: "Predicting TIR import/export traffic",
      category: "Time-series intelligence",
      description:
        "Built multi-layer LSTM ensembles to forecast cross-border trade lanes with holiday-aware features.",
      impact:
        "Cut planning variance by 35% and unlocked proactive staffing decisions.",
      metric: "MAE ↓21%",
      tags: ["Python", "LSTM", "TensorFlow", "Weights & Biases"],
    },
    {
      title: "Supermarket sales diagnosis",
      category: "Customer analytics",
      description:
        "Compared logistic regression vs. Naive Bayes to classify purchasing behaviors for 48 product families.",
      impact:
        "Surfaced top 6 levers that influenced repeat purchases and promo lift.",
      metric: "AUC ↑12%",
      tags: ["scikit-learn", "Pandas", "Feature engineering", "Explainability"],
    },
    {
      title: "Graph representation insights",
      category: "Network analysis",
      description:
        "Modeled relationships between entities to discover hidden communities and influence paths.",
      impact:
        "Accelerated onboarding by mapping decision flows and data owners.",
      metric: "Traversal time ↓40%",
      tags: ["Graph theory", "NetworkX", "Python", "Visualization"],
    },
    {
      title: "Carpooling platform database",
      category: "Operational data design",
      description:
        "Shipped a relational schema for managing riders, drivers, and reservations with audit-ready logging.",
      impact: "Enabled daily reporting and reduced booking errors.",
      metric: "Manual work ↓50%",
      tags: ["Database design", "SQL", "Access", "Data modeling"],
    },
  ];

  return (
    <section id='projects' className='section projects' data-animate>
      <div className='container'>
        <SectionHeader
          eyebrow='Projects'
          title='Representative case studies'
          subtitle='Each initiative balances statistical rigor with stakeholder clarity.'
        />
        <div className='projects-grid'>
          {projects.map((project) => (
            <ProjectCard key={project.title} project={project} />
          ))}
        </div>
      </div>
    </section>
  );
}

function Experience() {
  const experience = [
    {
      period: "2025 — Present",
      role: "Engineering Degree in Data Science & ML",
      org: "FSTM",
      detail:
        "Anticipated graduation in 2028 with an Engineering Degree in Data Science and Machine Learning, specializing in the design, deployment, and monitoring of production-ready ML systems using modern MLOps principles. The advanced curriculum provides deep expertise in Deep Learning and AI, including Generative AI, alongside mastery of distributed computing frameworks necessary for building reliable solutions within Big Data Ecosystems",
      signals: [
        "MLOPS",
        "DEEP LEARNING",
        "DISTRIBUTED COMPUTING",
        "AI",
        "BIG DATA",
        "GENERATIVE AI",
      ],
    },
    {
      period: "2024 — 2025(4 months)",
      role: "Data Scientist Intern",
      org: "Tanger Med Port Authority (TMPA)",
      detail:
        "Completed an intensive internship at Tanger Med Port Authority (TMPA), focusing on end-to-end data solutions and strategic reporting. Key achievements include the development and deployment of an LSTM Recurrent Neural Network for critical time series prediction (vessel traffic forecasting), providing management with operational insights to optimize port efficiency. This role involved managing the entire data lifecycle, from high-volume data cleaning and feature engineering to the design and maintenance of Power BI dashboards that transformed raw operational data into strategic Key Performance Indicators (KPIs).",
      signals: [
        "Pipeline reliability",
        "Dashboards",
        "Time-series",
        "LSTM",
        "BIG DATA",
        "NLP",
      ],
    },
    {
      period: "2021-2024",
      role: "Bachelor Degree in Data Analysis",
      org: "FSTT",
      detail:
        "Graduated in 2025 with a Bachelor Degree in Data Analysis, establishing a strong foundation in statistical modeling, data wrangling, and business intelligence. This comprehensive training focused on leveraging inferential and descriptive statistics to test hypotheses, while mastering ETL processes and data preparation techniques crucial for building reliable ML features, alongside developing actionable Power BI/Tableau dashboards for stakeholder communication",
      signals: ["POWER BI", "PYTHON", "MACHINE LEARNING", "SQL", "STATISTICS"],
    },
  ];

  return (
    <section id='experience' className='section' data-animate>
      <div className='container'>
        <SectionHeader
          eyebrow='Experience'
          title='Journey so far'
          subtitle='A mix of internships and academic rigor.'
        />
        <div className='experience-timeline'>
          {experience.map((item) => (
            <article key={item.role} className='experience-card'>
              <div className='experience-meta'>
                <span>{item.period}</span>
                <p>{item.org}</p>
              </div>
              <div>
                <h3>{item.role}</h3>
                <p className='experience-detail'>{item.detail}</p>
                <div className='experience-tags'>
                  {item.signals.map((signal) => (
                    <span key={signal}>{signal}</span>
                  ))}
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function Contact() {
  const [status, setStatus] = useState(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    setStatus("success");
    event.target.reset();
  };

  return (
    <section id='contact' className='section' data-animate>
      <div className='container contact-shell'>
        <article className='contact-panel'>
          <SectionHeader
            eyebrow='Contact'
            title='Let’s build something measurable'
            subtitle='Open to full-time roles, advisory engagements, and collaborative research.'
          />
          <ul className='contact-list'>
            <li>
              <span>Response time</span>
              <p>within 24h on weekdays</p>
            </li>
            <li>
              <span>Formats</span>
              <p>Slack · Teams · Notion · Workshops</p>
            </li>
            <li>
              <span>Availability</span>
              <p>Remote · Hybrid · Client on-site</p>
            </li>
          </ul>
          <div className='contact-links'>
            <a
              href='https://www.linkedin.com/in/adam-arbai-186110281?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BdmAKRQNTTYqJCUQXa5PWSg%3D%3D'
              target='_blank'
              rel='noopener noreferrer'>
              LinkedIn ↗
            </a>
          </div>
        </article>

        <form className='contact-form' onSubmit={handleSubmit}>
          <div className='form-row'>
            <label className='form-field'>
              <span>Name</span>
              <input type='text' name='name' placeholder='Your name' required />
            </label>
            <label className='form-field'>
              <span>Email</span>
              <input
                type='email'
                name='email'
                placeholder='you@example.com'
                required
              />
            </label>
          </div>
          <label className='form-field'>
            <span>Project / Topic</span>
            <input
              type='text'
              name='topic'
              placeholder='What should we explore?'
              required
            />
          </label>
          <label className='form-field'>
            <span>Message</span>
            <textarea
              name='message'
              rows='4'
              placeholder='Share context, goals, timelines...'
              required
            />
          </label>
          <button type='submit' className='button button-solid'>
            Send message
          </button>
          {status === "success" && (
            <p className='form-status success'>Thanks for reaching out!</p>
          )}
        </form>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className='footer'>
      <div className='container footer-shell'>
        <p>© {new Date().getFullYear()} Adam Arbai · Built with care.</p>
        <div className='footer-links'>
          <a
            href='https://www.linkedin.com/in/adam-arbai-186110281?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BdmAKRQNTTYqJCUQXa5PWSg%3D%3D'
            target='_blank'
            rel='noopener noreferrer'>
            LinkedIn
          </a>
          <a href='#' onClick={(e) => e.preventDefault()}>
            GitHub
          </a>
          <a href='#' onClick={(e) => e.preventDefault()}>
            Email
          </a>
        </div>
      </div>
    </footer>
  );
}

function App() {
  useReveal();

  return (
    <>
      <Navbar />
      <main>
        <Hero />
        <StackShowcase />
        <About />
        <Capabilities />
        <Projects />
        <Experience />
        <Contact />
      </main>
      <Footer />
    </>
  );
}

const rootEl = document.getElementById("root");
const root = ReactDOM.createRoot(rootEl);
root.render(<App />);
