"use client";

import { useEffect, useState } from "react";

type HeroImage = {
  id: number;
  image: string;
};

type HeroData = {
  id: number;
  badge: string | null;
  title: string;
  highlight: string | null;
  description: string | null;

  primaryButtonText: string | null;
  primaryButtonUrl: string | null;

  secondaryButtonText: string | null;
  secondaryButtonUrl: string | null;

  photo: string | null;

  githubUrl: string | null;
  linkedinUrl: string | null;
  email: string | null;

  cv: string | null;

  active: boolean;

  heroimage: HeroImage[];
};

export default function Hero() {
  const [hero, setHero] = useState<HeroData | null>(null);
  const [currentImage, setCurrentImage] = useState(0);

  const [touchStart, setTouchStart] = useState<number | null>(
    null
  );

  const [touchEnd, setTouchEnd] = useState<number | null>(
    null
  );

  /*
   * ==========================================================
   * LOAD HERO DATA
   * ==========================================================
   */

  useEffect(() => {
    const loadHero = async () => {
      try {
        const response = await fetch("/api/hero", {
          cache: "no-store",
        });

        const result = await response.json();

        if (!response.ok || !result.success) {
          throw new Error(
            result.message || "Gagal mengambil data Hero."
          );
        }

        const heroData = Array.isArray(result.data)
          ? result.data.find(
              (item: HeroData) => item.active
            ) ?? result.data[0]
          : result.data;

        if (heroData) {
          setHero(heroData);
          setCurrentImage(0);
        }
      } catch (error) {
        console.error(
          "Gagal mengambil data Hero:",
          error
        );
      }
    };

    loadHero();
  }, []);

  /*
   * ==========================================================
   * AUTO SLIDE
   * ==========================================================
   *
   * Semua Hooks tetap dipanggil sebelum if (!hero)
   * untuk mencegah React Rules of Hooks error.
   */

  useEffect(() => {
    if (!hero) return;

    const images = hero.heroimage ?? [];

    if (images.length <= 1) return;

    const interval = setInterval(() => {
      setCurrentImage((prev) =>
        prev >= images.length - 1
          ? 0
          : prev + 1
      );
    }, 3000);

    return () => {
      clearInterval(interval);
    };
  }, [hero]);

  /*
   * ==========================================================
   * IMAGE NAVIGATION
   * ==========================================================
   */

  const nextImage = () => {
    if (!hero) return;

    const images = hero.heroimage ?? [];

    if (images.length <= 1) return;

    setCurrentImage((prev) =>
      prev >= images.length - 1
        ? 0
        : prev + 1
    );
  };

  const previousImage = () => {
    if (!hero) return;

    const images = hero.heroimage ?? [];

    if (images.length <= 1) return;

    setCurrentImage((prev) =>
      prev <= 0
        ? images.length - 1
        : prev - 1
    );
  };

  /*
   * ==========================================================
   * TOUCH / SWIPE
   * ==========================================================
   */

  const handleTouchStart = (
    event: React.TouchEvent<HTMLDivElement>
  ) => {
    setTouchStart(
      event.targetTouches[0].clientX
    );

    setTouchEnd(null);
  };

  const handleTouchMove = (
    event: React.TouchEvent<HTMLDivElement>
  ) => {
    setTouchEnd(
      event.targetTouches[0].clientX
    );
  };

  const handleTouchEnd = () => {
    if (
      touchStart === null ||
      touchEnd === null ||
      !hero
    ) {
      return;
    }

    const images = hero.heroimage ?? [];

    if (images.length <= 1) {
      setTouchStart(null);
      setTouchEnd(null);
      return;
    }

    const distance = touchStart - touchEnd;

    const minimumSwipeDistance = 50;

    if (distance > minimumSwipeDistance) {
      nextImage();
    }

    if (distance < -minimumSwipeDistance) {
      previousImage();
    }

    setTouchStart(null);
    setTouchEnd(null);
  };

  /*
   * ==========================================================
   * RENDER CONDITION
   * ==========================================================
   */

  if (!hero) {
    return null;
  }

  const images = hero.heroimage ?? [];

  const currentPhoto =
    images.length > 0
      ? images[currentImage]?.image
      : hero.photo;

  return (
    <>
      <section
        id="home"
        className="hero-section"
      >
        <div className="container">
          <div className="row align-items-center hero-row">

            {/* =====================================================
                LEFT CONTENT
            ====================================================== */}

            <div className="col-12 col-lg-7">
              <div className="hero-content">

                {/* BADGE */}

                {hero.badge && (
                  <div className="hero-badge-wrapper">
                    <span className="hero-badge">
                      <i className="bi bi-code-slash"></i>

                      <span>
                        {hero.badge}
                      </span>
                    </span>
                  </div>
                )}

                {/* TITLE */}

                <h1 className="hero-title">
                  {hero.title}
                </h1>

                {/* HIGHLIGHT */}

                {hero.highlight && (
                  <h2 className="hero-highlight">
                    {hero.highlight}
                  </h2>
                )}

                {/* DESCRIPTION */}

                {hero.description && (
                  <p className="hero-description">
                    {hero.description}
                  </p>
                )}

                {/* BUTTONS */}

                {(hero.primaryButtonText ||
                  hero.secondaryButtonText ||
                  hero.cv) && (
                  <div className="hero-buttons">

                    {/* PRIMARY */}

                    {hero.primaryButtonText &&
                      hero.primaryButtonUrl && (
                        <a
                          href={hero.primaryButtonUrl}
                          className="btn hero-btn-primary"
                        >
                          <span>
                            {hero.primaryButtonText}
                          </span>

                          <i className="bi bi-arrow-up-right"></i>
                        </a>
                      )}

                    {/* SECONDARY */}

                    {hero.secondaryButtonText &&
                      hero.secondaryButtonUrl && (
                        <a
                          href={hero.secondaryButtonUrl}
                          className="btn hero-btn-secondary"
                        >
                          <i className="bi bi-chat-dots"></i>

                          <span>
                            {hero.secondaryButtonText}
                          </span>
                        </a>
                      )}

                    {/* CV */}

                    {hero.cv && (
                      <a
                        href={hero.cv}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="btn hero-btn-cv"
                      >
                        <i className="bi bi-file-earmark-pdf"></i>

                        <span>
                          View My CV
                        </span>
                      </a>
                    )}

                  </div>
                )}

                {/* INFORMATION */}

                <div className="hero-meta">

                  <div className="hero-meta-item">
                    <i className="bi bi-check-circle-fill"></i>

                    <span>
                      Available for opportunities
                    </span>
                  </div>

                  <div className="hero-meta-item">
                    <i className="bi bi-stars"></i>

                    <span>
                      Building modern digital solutions
                    </span>
                  </div>

                </div>

              </div>
            </div>

            {/* =====================================================
                RIGHT PROFILE
            ====================================================== */}

            <div className="col-12 col-lg-5">

              <div className="profile-wrapper">

                <div className="profile-card">

                  {/* =================================================
                      RUNNING TOP LINE
                  ================================================== */}

                  <div className="profile-card-line">
                    <span></span>
                  </div>

                  {/* =================================================
                      PROFILE HEADER
                  ================================================== */}

                  <div className="profile-header">

                    <div className="profile-label">

                      <span className="profile-status"></span>

                      <span>
                        PROFILE
                      </span>

                    </div>

                    <span className="profile-number">
                      01
                    </span>

                  </div>

                  {/* =================================================
                      IMAGE
                  ================================================== */}

                  <div
                    className="profile-image-wrapper"
                    onTouchStart={handleTouchStart}
                    onTouchMove={handleTouchMove}
                    onTouchEnd={handleTouchEnd}
                  >

                    <div className="profile-image">

                      {currentPhoto ? (
                        <img
                          key={currentPhoto}
                          src={currentPhoto}
                          alt={
                            hero.highlight ||
                            hero.title
                          }
                          className="profile-image-element"
                        />
                      ) : (
                        <div className="profile-placeholder">
                          <i className="bi bi-person"></i>
                        </div>
                      )}

                    </div>

                  </div>

                  {/* =================================================
                      PROFILE INFORMATION
                  ================================================== */}

                  <div className="profile-information">

                    <h2 className="profile-title">
                      {hero.title}
                    </h2>

                    {hero.highlight && (
                      <p className="profile-highlight">
                        {hero.highlight}
                      </p>
                    )}

                  </div>

                  {/* =================================================
                      DIVIDER
                  ================================================== */}

                  <div className="profile-divider"></div>

                  {/* =================================================
                      SOCIAL MEDIA
                  ================================================== */}

                  {(hero.githubUrl ||
                    hero.linkedinUrl ||
                    hero.email) && (
                    <div className="profile-social">

                      {hero.githubUrl && (
                        <a
                          href={hero.githubUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="social-item"
                          aria-label="GitHub"
                          title="GitHub"
                        >
                          <i className="bi bi-github"></i>
                        </a>
                      )}

                      {hero.linkedinUrl && (
                        <a
                          href={hero.linkedinUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="social-item"
                          aria-label="LinkedIn"
                          title="LinkedIn"
                        >
                          <i className="bi bi-linkedin"></i>
                        </a>
                      )}

                      {hero.email && (
                        <a
                          href={`mailto:${hero.email}`}
                          className="social-item"
                          aria-label="Email"
                          title={hero.email}
                        >
                          <i className="bi bi-envelope"></i>
                        </a>
                      )}

                    </div>
                  )}

                  {/* =================================================
                      FOOTER
                  ================================================== */}

                  <div className="profile-footer">

                    <span>
                      GloVaTech
                    </span>

                    <span>
                      <i className="bi bi-arrow-up-right"></i>
                    </span>

                  </div>

                </div>

              </div>

            </div>

          </div>
        </div>
      </section>

      {/* ==========================================================
          STYLES
      =========================================================== */}

      <style jsx>{`

        /* ==========================================================
           HERO
        =========================================================== */

        .hero-section {
          position: relative;

          width: 100%;

          min-height: 100vh;

          background: #ffffff;

          overflow: hidden;
        }

        .hero-row {
          min-height: 100vh;

          padding-top: 100px;
          padding-bottom: 80px;
        }

        /* ==========================================================
           LEFT CONTENT
        =========================================================== */

        .hero-content {
          width: 100%;

          max-width: 760px;
        }

        .hero-badge-wrapper {
          margin-bottom: 22px;

          text-align: center;
        }

        .hero-badge {
          display: inline-flex;

          align-items: center;

          gap: 8px;

          padding: 7px 14px;

          border: 1px solid
            rgba(25, 135, 84, 0.35);

          border-radius: 50px;

          background: #ffffff;

          color: #198754;

          font-size: 0.78rem;

          font-weight: 600;

          box-shadow:
            0 5px 18px
              rgba(25, 135, 84, 0.06);
        }

        .hero-badge i {
          font-size: 0.9rem;
        }

        /* ==========================================================
           TITLE
        =========================================================== */

        .hero-title {
          margin: 0;

          color: #17221c;

          font-size: clamp(
            2.4rem,
            5vw,
            4.5rem
          );

          line-height: 1.05;

          font-weight: 800;

          letter-spacing: -0.045em;

          text-align: center;
        }

        /* ==========================================================
           HIGHLIGHT
        =========================================================== */

        .hero-highlight {
          margin: 18px auto 0;

          max-width: 700px;

          color: #198754;

          font-size: clamp(
            1.25rem,
            2.2vw,
            2rem
          );

          line-height: 1.35;

          font-weight: 700;

          letter-spacing: -0.02em;

          text-align: center;
        }

        /* ==========================================================
           DESCRIPTION
        =========================================================== */

        .hero-description {
          max-width: 700px;

          margin: 25px auto 0;

          color: #626d67;

          font-size: clamp(
            0.9rem,
            1.2vw,
            1.05rem
          );

          line-height: 1.85;

          text-align: justify;

          text-justify: inter-word;
        }

        /* ==========================================================
           BUTTONS
        =========================================================== */

        .hero-buttons {
          display: flex;

          justify-content: center;
          align-items: center;

          flex-wrap: wrap;

          gap: 12px;

          margin-top: 30px;
        }

        .hero-btn-primary,
        .hero-btn-secondary,
        .hero-btn-cv {
          min-height: 48px;

          padding: 0 18px;

          border-radius: 10px;

          display: inline-flex;

          align-items: center;
          justify-content: center;

          gap: 9px;

          font-size: 0.9rem;

          font-weight: 600;

          transition:
            all 0.25s ease;
        }

        .hero-btn-primary {
          color: #ffffff;

          background: #198754;

          border: 1px solid #198754;
        }

        .hero-btn-primary:hover {
          color: #ffffff;

          background: #157347;

          border-color: #157347;

          transform:
            translateY(-2px);
        }

        .hero-btn-secondary {
          color: #198754;

          background: #ffffff;

          border: 1px solid #198754;
        }

        .hero-btn-secondary:hover {
          color: #ffffff;

          background: #198754;

          border-color: #198754;

          transform:
            translateY(-2px);
        }

        .hero-btn-cv {
          color: #343a40;

          background: #ffffff;

          border: 1px solid #d9dfdc;
        }

        .hero-btn-cv:hover {
          color: #198754;

          border-color: #198754;

          transform:
            translateY(-2px);
        }

        /* ==========================================================
           META
        =========================================================== */

        .hero-meta {
          display: flex;

          justify-content: center;
          align-items: center;

          flex-wrap: wrap;

          gap: 12px 25px;

          margin-top: 28px;

          color: #7a847e;

          font-size: 0.78rem;
        }

        .hero-meta-item {
          display: flex;

          align-items: center;

          gap: 7px;
        }

        .hero-meta-item i {
          color: #198754;

          font-size: 0.8rem;
        }

        /* ==========================================================
           PROFILE WRAPPER
        =========================================================== */

        .profile-wrapper {
          width: 100%;

          max-width: 440px;

          margin: 0 auto;
        }

        /* ==========================================================
           PROFILE CARD
        =========================================================== */

        .profile-card {
          position: relative;

          width: 100%;

          padding: 28px;

          overflow: hidden;

          background: #ffffff;

          border: 1px solid
            rgba(25, 135, 84, 0.62);

          border-radius: 20px;

          box-shadow:
            0 15px 40px
              rgba(25, 50, 38, 0.08),

            0 0 0 1px
              rgba(25, 135, 84, 0.05);

          transition:
            transform 0.35s ease,
            border-color 0.35s ease,
            box-shadow 0.35s ease;
        }

        .profile-card:hover {
          transform:
            translateY(-4px);

          border-color:
            rgba(25, 135, 84, 0.9);

          box-shadow:
            0 22px 55px
              rgba(25, 50, 38, 0.11),

            0 0 0 1px
              rgba(25, 135, 84, 0.08);
        }

        /* ==========================================================
           RUNNING TOP LINE
        =========================================================== */

        .profile-card-line {
          position: absolute;

          top: 0;
          left: 0;

          width: 100%;
          height: 3px;

          overflow: hidden;

          background:
            rgba(25, 135, 84, 0.14);

          z-index: 10;
        }

        .profile-card-line span {
          position: absolute;

          top: 0;
          left: -45%;

          width: 45%;
          height: 3px;

          border-radius: 999px;

          background:
            linear-gradient(
              90deg,
              transparent,
              #198754 20%,
              #20c997 50%,
              #198754 80%,
              transparent
            );

          box-shadow:
            0 0 12px
              rgba(25, 135, 84, 0.6);

          animation:
            profileCardEnergy
            2.5s linear infinite;
        }

        @keyframes profileCardEnergy {

          0% {
            left: -45%;
          }

          100% {
            left: 100%;
          }

        }

        /* ==========================================================
           PROFILE HEADER
        =========================================================== */

        .profile-header {
          display: flex;

          align-items: center;
          justify-content: space-between;

          margin-bottom: 24px;
        }

        .profile-label {
          display: flex;

          align-items: center;

          gap: 8px;

          color: #6f7973;

          font-size: 0.7rem;

          font-weight: 700;

          letter-spacing: 0.15em;
        }

        .profile-status {
          width: 7px;
          height: 7px;

          flex-shrink: 0;

          border-radius: 50%;

          background: #198754;

          box-shadow:
            0 0 0 4px
              rgba(25, 135, 84, 0.1);
        }

        .profile-number {
          color: #198754;

          font-size: 0.7rem;

          font-weight: 700;

          letter-spacing: 0.1em;
        }

        /* ==========================================================
           IMAGE
        =========================================================== */

        .profile-image-wrapper {
          position: relative;

          width: 100%;

          aspect-ratio: 1 / 1;

          margin: 0 auto;

          overflow: visible;

          touch-action: pan-y;

          user-select: none;
        }

        .profile-image {
          width: 100%;
          height: 100%;

          overflow: hidden;

          border-radius: 14px;

          background: #f8f9f8;

          border: 1px solid
            rgba(25, 135, 84, 0.38);

          box-shadow:
            0 12px 30px
              rgba(0, 0, 0, 0.08);

          transition:
            border-color 0.3s ease,
            box-shadow 0.3s ease;
        }

        .profile-card:hover .profile-image {
          border-color:
            rgba(25, 135, 84, 0.55);

          box-shadow:
            0 15px 35px
              rgba(25, 135, 84, 0.08);
        }

        .profile-image-element {
          width: 100%;
          height: 100%;

          display: block;

          object-fit: cover;

          object-position: center;

          animation:
            profileImageFade
            0.55s ease;
        }

        @keyframes profileImageFade {

          from {
            opacity: 0.35;

            transform:
              scale(1.015);
          }

          to {
            opacity: 1;

            transform:
              scale(1);
          }

        }

        .profile-placeholder {
          width: 100%;
          height: 100%;

          display: flex;

          align-items: center;
          justify-content: center;

          color: #198754;

          font-size: 5rem;

          background:
            linear-gradient(
              135deg,
              #f8faf9,
              #eef7f2
            );
        }

        /* ==========================================================
           IMAGE NAVIGATION
        =========================================================== */

        

        /* ==========================================================
           HIDE PAGINATION
        =========================================================== */

        .profile-pagination,
        .profile-dots,
        .pagination-dots,
        .hero-pagination,
        .hero-dots,
        .swiper-pagination {
          display: none !important;

          visibility: hidden !important;

          opacity: 0 !important;

          pointer-events: none !important;
        }

        /* ==========================================================
           PROFILE INFORMATION
        =========================================================== */

        .profile-information {
          margin-top: 22px;

          text-align: center;
        }

        .profile-title {
          margin: 0;

          color: #17221c;

          font-size: clamp(
            1.25rem,
            2vw,
            1.6rem
          );

          line-height: 1.3;

          font-weight: 750;
        }

        .profile-highlight {
          margin: 8px 0 0;

          color: #198754;

          font-size: 0.88rem;

          line-height: 1.5;

          font-weight: 600;

          text-align: center;
        }

        /* ==========================================================
           DIVIDER
        =========================================================== */

        .profile-divider {
          width: 100%;
          height: 1px;

          margin: 22px 0;

          background:
            rgba(25, 135, 84, 0.16);
        }

        /* ==========================================================
           SOCIAL
        =========================================================== */

        .profile-social {
          display: flex;

          justify-content: center;
          align-items: center;

          gap: 10px;
        }

        .social-item {
          width: 40px;
          height: 40px;

          display: flex;

          align-items: center;
          justify-content: center;

          color: #59635d;

          background: #ffffff;

          border: 1px solid
            rgba(25, 135, 84, 0.3);

          border-radius: 10px;

          text-decoration: none;

          transition:
            all 0.25s ease;
        }

        .social-item:hover {
          color: #ffffff;

          background: #198754;

          border-color: #198754;

          transform:
            translateY(-2px);

          box-shadow:
            0 7px 16px
              rgba(25, 135, 84, 0.18);
        }

        /* ==========================================================
           PROFILE FOOTER
        =========================================================== */

        .profile-footer {
          display: flex;

          align-items: center;
          justify-content: space-between;

          margin-top: 22px;

          padding-top: 15px;

          border-top:
            1px solid
            rgba(25, 135, 84, 0.14);

          color: #98a19b;

          font-size: 0.68rem;

          font-weight: 700;

          letter-spacing: 0.08em;

          text-transform: uppercase;
        }

        .profile-footer span:last-child {
          color: #198754;
        }

        /* ==========================================================
           TABLET
        =========================================================== */

        @media (max-width: 991.98px) {

          .hero-row {
            min-height: auto;

            padding-top: 110px;
            padding-bottom: 70px;
          }

          .hero-content {
            max-width: 760px;

            margin: 0 auto;

            text-align: center;
          }

          .hero-description {
            margin-left: auto;
            margin-right: auto;
          }

          .profile-wrapper {
            margin-top: 45px;
          }

          .profile-card {
            max-width: 440px;

            margin: 0 auto;
          }

        }

        /* ==========================================================
           MOBILE
        =========================================================== */

        @media (max-width: 575.98px) {

          .hero-section {
            min-height: auto;
          }

          .hero-row {
            padding-top: 90px;
            padding-bottom: 50px;
          }

          .hero-badge-wrapper {
            margin-bottom: 18px;
          }

          .hero-title {
            font-size: clamp(
              2rem,
              10vw,
              2.8rem
            );

            line-height: 1.08;

            letter-spacing: -0.04em;

            text-align: center;
          }

          .hero-highlight {
            margin-top: 14px;

            font-size: clamp(
              1.05rem,
              5vw,
              1.35rem
            );

            line-height: 1.4;

            text-align: center;
          }

          /* ========================================================
             DESCRIPTION
          ========================================================= */

          .hero-description {
            margin-top: 20px;

            font-size: 0.88rem;

            line-height: 1.8;

            text-align: justify;

            text-justify: inter-word;
          }

          /* ========================================================
             BUTTONS
          ========================================================= */

          .hero-buttons {
            width: 100%;

            flex-direction: column;

            align-items: stretch;

            gap: 10px;

            margin-top: 25px;
          }

          .hero-btn-primary,
          .hero-btn-secondary,
          .hero-btn-cv {
            width: 100%;

            min-height: 48px;
          }

          /* ========================================================
             META
          ========================================================= */

          .hero-meta {
            flex-direction: column;

            align-items: center;

            gap: 9px;

            margin-top: 24px;

            font-size: 0.72rem;

            text-align: center;
          }

          /* ========================================================
             PROFILE
          ========================================================= */

          .profile-wrapper {
            margin-top: 30px;
          }

          .profile-card {
            padding: 20px 15px;

            border-radius: 17px;
          }

          .profile-card-line {
            height: 2px;
          }

          .profile-card-line span {
            height: 2px;
          }

          .profile-header {
            margin-bottom: 20px;
          }

          .profile-image-wrapper {
            aspect-ratio: 1 / 1;
          }

          .profile-image {
            border-radius: 13px;
          }

          /* ========================================================
             NAVIGATION
          ========================================================= */

          .profile-title {
            font-size: 1.2rem;
          }

          .profile-highlight {
            font-size: 0.8rem;
          }

          .social-item {
            width: 38px;
            height: 38px;
          }

        }

        /* ==========================================================
           SMALL MOBILE
        =========================================================== */

        @media (max-width: 375px) {

          .hero-row {
            padding-top: 82px;
            padding-bottom: 45px;
          }

          .hero-title {
            font-size: 1.9rem;
          }

          .hero-highlight {
            font-size: 1rem;
          }

          .hero-description {
            font-size: 0.84rem;

            line-height: 1.75;
          }

          .profile-card {
            padding: 18px 12px;
          }

          .profile-social {
            gap: 7px;
          }

          .social-item {
            width: 36px;
            height: 36px;
          }

        }

        /* ==========================================================
           REDUCED MOTION
        =========================================================== */

        @media (prefers-reduced-motion: reduce) {

          .profile-card-line span,
          .profile-image-element {
            animation: none;
          }

          .profile-card,
          .profile-nav,
          .social-item,
          .hero-btn-primary,
          .hero-btn-secondary,
          .hero-btn-cv {
            transition: none;
          }

        }

      `}</style>
    </>
  );
}