"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import styles from "../../page.module.css";
import {
  ArrowDown,
  ArrowRight,
  ArrowUpRight,
  Bot,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Code2,
  Cpu,
  KeyRound,
  Layers,
  Lock,
  Megaphone,
  Network,
  Quote,
  Server,
  ShieldCheck,
  Star,
  User,
  UserCheck,
  Workflow,
} from "lucide-react";
import { UniNetLogo, CraftWave, TaskFlowLogo, MeliorateCRMLogo, Human2HumanLogo } from "@/app/lib/icons";
import { FadeUp, Stagger, StaggerItem } from "../Motion/Motion";

import { Header } from "../Header/Header";
import { Footer } from "../Footer/Footer";
import BloomBackground from "../BloomBackground/BloomBackground";
import { CaseStudyCard } from "../CaseStudyCard/CaseStudyCard";
import { PROJECTS, type ProjectIcon } from "../../lib/data/projects";
import { CASE_STUDIES } from "../../lib/data/case-studies";

const productIconMap: Record<ProjectIcon, React.ComponentType<{ size?: number }>> = {
  UniNetLogo: UniNetLogo,
  CraftWave: CraftWave,
  TaskFlowLogo: TaskFlowLogo,
  MeliorateCRMLogo: MeliorateCRMLogo,
  Human2HumanLogo: Human2HumanLogo,
};

const CUSTOM_SOLUTIONS = [
  {
    title: "Custom Software Platforms",
    description:
      "From internal portals to client-facing products, we design and build software tailored to your exact business model.",
    icon: Code2,
  },
  {
    title: "Agentic AI",
    description:
      "Task-specific AI agents for research, sales, recruiting, and operations — architected, evaluated, and kept human-in-the-loop. Reliability from architecture, not model magic.",
    icon: Bot,
  },
  {
    title: "Automation Systems",
    description:
      "Replace repetitive manual processes with event-driven workflows, smart routing, and reliable orchestration.",
    icon: Workflow,
  },
  {
    title: "Marketing Systems",
    description:
      "Build performance-focused growth infrastructure including lead capture, nurture flows, campaign ops, and reporting.",
    icon: Megaphone,
  },
];

type ResearchThread = {
  title: string;
  description: string;
  icon: React.ComponentType<{ size?: number }>;
};

const RESEARCH_THREADS: ResearchThread[] = [
  {
    title: "Applied ontology",
    description:
      "A shared, machine-usable model of the entities, identities, and relationships a system runs on — the data and identity layer underneath distributed multi-chain infrastructure.",
    icon: Network,
  },
  {
    title: "Agentic reliability",
    description:
      "An agent is a system to be architected, evaluated, and kept human-in-the-loop — not a prompt to be tuned.",
    icon: Bot,
  },
  {
    title: "Context engineering",
    description:
      "Curating exactly what a model sees, remembers, and retrieves at each step — the named practice (2025) that keeps agents dependable.",
    icon: Layers,
  },
];

type TrustMarker = {
  title: string;
  description: string;
  icon: React.ComponentType<{ size?: number }>;
};

const TRUST_MARKERS: TrustMarker[] = [
  {
    title: "Memory-safe engineering",
    description: "Core systems built in memory-safe Rust, with unsafe code denied at the compiler.",
    icon: Cpu,
  },
  {
    title: "Security by design",
    description: "Fail-closed defaults — systems refuse by default rather than act on a half-verified state.",
    icon: ShieldCheck,
  },
  {
    title: "EU data sovereignty",
    description: "Self-hostable models and on-device processing keep regulated data inside your own boundary.",
    icon: Server,
  },
  {
    title: "GDPR + EU AI Act aligned",
    description: "AES-256-GCM encryption and immutable audit logging, reflected in our shipped platforms.",
    icon: Lock,
  },
  {
    title: "Human in the loop",
    description: "Guardrailed, evaluated autonomy — with oversight built in, the way regulated work expects.",
    icon: UserCheck,
  },
  {
    title: "Threshold cryptography",
    description: "Threshold key management and zero-knowledge techniques, so no single node holds the whole secret.",
    icon: KeyRound,
  },
];

/* The first BIO_PREVIEW paragraphs show by default; the rest sit behind the
   Read more toggle. */
const ADRIAN_BIO = [
  "Adrian Stavljenić is an engineer and entrepreneur from Zagreb, with more than a decade spent building production software and AI systems. He is co-founder and lead AI systems engineer at Human2Human, where he designed and built an agentic AI platform from the ground up — a system in which AI agents plan, delegate, and carry out complex workflows on their own.",
  "He specialises in multi-agent orchestration, context engineering, long-term memory systems, MCP integrations, semantic retrieval, and the security and governance of AI systems inside a business.",
  "His background is as broad as it is deep: distributed systems, blockchain architecture, Rust, and Linux infrastructure. He led three years of research and the whitepaper behind UniNet, and as lead engineer delivered the Web3 platform for Fifth & Nine, a Delaware-incorporated US startup that raised one million dollars.",
  "Through his own agency, Meliorate, he has delivered more than 50 projects — from SaaS platforms and payment systems to automations and integrations. An earlier career in design and visual communication gives him an unusual advantage: explaining complicated things clearly.",
  "As a lecturer at the Human2Human school, Adrian teaches only what he has built and run in production himself. What students take away is not just the tooling but the reasoning behind it: how AI systems are designed, how control and trust get built into them, and what it takes to move from a demo to something that genuinely works.",
];

const BIO_PREVIEW = 2;

const EXPERT_TAGS = [
  "AI Automation Architecture",
  "Corporate AI Adoption",
  "System Development",
  "Lecturer & Educator",
  "Enterprise Consulting",
];

const GUARDRAILS = [
  "Structured outputs",
  "Evals",
  "Human-in-the-loop",
  "Role-based access",
  "Tenant isolation",
  "Audit logging",
  "Token & cost governance",
  "Permissioned tools",
  "Fail-closed defaults",
  "ISO/IEC 42001 alignment",
];

type Review = {
  quote: string;
  name: string;
  role: string;
  badge?: string;
};

const REVIEWS: Review[] = [
  {
    quote:
      "Adrian has been the best person I've worked with. A developer on the next level, but also a creative flare for design. He has gone above and beyond my expectations.",
    name: "Simon Brooker",
    role: "Verified Google Review",
    badge: "New",
  },
  {
    quote:
      "We worked with Meliorate on the development of custom software tailored to our business needs, including AI-powered functionality, and we are very satisfied with the collaboration.",
    name: "R Vee",
    role: "Verified Google Review",
  },
  {
    quote:
      "I have always been very satisfied with Meliorate's services. After several years of work entrusted to them, the quality has always been excellent. Very professional and reliable.",
    name: "Unchain Academy",
    role: "Verified Google Review",
  },
  {
    quote:
      "Adrian did a fantastic job of creating an excellent diagram architecture for my sales lectures. He made it extremely easy to put a complicated flow chart together, that really outlined the whole sales structure that I teach. The experience was effortless and the results were superb.",
    name: "Ian Genius",
    role: "Sales Trainer, Financial Services",
  },
  {
    quote:
      "Adrian has been a great partner over the past few years. He has a solid work ethic, hits delivery dates, understands the business objectives at hand and asks relevant questions.",
    name: "Robert Weiss",
    role: "Verified Google Review",
  },
  {
    quote:
      "Adrian has a great attitude and drives to continuously improve and fine-tune his skills. He comes with new insights each time, consistently improving and learning. He is on his way to delivering even more value for those who enter business cooperation with him and Meliorate.",
    name: "Giovanni Rodriguez",
    role: "Verified Google Review",
  },
];

export default function HomepageContent() {
  const words = ["Entrepreneurs.", "Companies.", "Creators.", "Executives.", "Visionaries."];
  // The first word repeated at the end. The reel always travels forwards into
  // it, then snaps back to the real first word with the transition suppressed -
  // previously the index wrapped with %, so every fourth cycle visibly rewound
  // backwards through every word. Sizes are derived, so the word count is no
  // longer load-bearing on hardcoded CSS percentages.
  const reel = [...words, words[0]];
  const [index, setIndex] = useState(0);
  const [sliding, setSliding] = useState(true);
  const [bioExpanded, setBioExpanded] = useState(false);

  const reviewTrackRef = useRef<HTMLDivElement>(null);
  const [reviewIndex, setReviewIndex] = useState(0);
  const [canPrev, setCanPrev] = useState(false);
  const [canNext, setCanNext] = useState(true);

  useEffect(() => {
    // Rotate the hero words regardless of reduced-motion / low-power mode -
    // this word-cycle is a core part of the hero and was freezing on laptops
    // and phones in battery-saver mode.
    const interval = setInterval(() => {
      setIndex((prev) => prev + 1);
    }, 3000);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    // Landed on the duplicate first word: once its slide finishes, jump back to
    // the real one with the transition off so the reset is invisible.
    if (index !== words.length) return;
    const timer = setTimeout(() => {
      setSliding(false);
      setIndex(0);
    }, 1200);
    return () => clearTimeout(timer);
  }, [index, words.length]);

  useEffect(() => {
    if (sliding) return;
    // Restore the transition once the snap has applied. Deliberately a timer
    // and not requestAnimationFrame: rAF is paused in a backgrounded tab, so
    // the reel could park with its transition disabled and then jump between
    // words instead of sliding. Timers still fire (throttled) when hidden, and
    // 50ms is far inside the 3s gap before the next word.
    const timer = setTimeout(() => setSliding(true), 50);
    return () => clearTimeout(timer);
  }, [sliding]);

  const reviewStep = () => {
    const track = reviewTrackRef.current;
    const first = track?.firstElementChild as HTMLElement | null;
    return first ? first.offsetWidth + 18 : 320;
  };

  const scrollReviews = (dir: number) => {
    const track = reviewTrackRef.current;
    if (!track) return;
    track.scrollBy({ left: dir * reviewStep(), behavior: "smooth" });
  };

  const goToReview = (i: number) => {
    const track = reviewTrackRef.current;
    const el = track?.children[i] as HTMLElement | undefined;
    el?.scrollIntoView({ inline: "start", block: "nearest", behavior: "smooth" });
  };

  const updateReviewNav = () => {
    const track = reviewTrackRef.current;
    if (!track) return;
    setReviewIndex(Math.round(track.scrollLeft / reviewStep()));
    setCanPrev(track.scrollLeft > 4);
    setCanNext(track.scrollLeft + track.clientWidth < track.scrollWidth - 4);
  };

  useEffect(() => {
    updateReviewNav();
    window.addEventListener("resize", updateReviewNav);
    return () => window.removeEventListener("resize", updateReviewNav);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <main className={styles.pageWrapper}>
      <Header />

      <div className={styles.sliderArea}>
        <div className={styles.heroBgWrap}>
          <BloomBackground className={styles.heroBloom} />
          <div className={styles.heroBgOverlay} />
        </div>
        <div className={styles.heroInner}>
          <div className={styles.container}>
            <div className={`${styles.row} ${styles.alignItemsCenter}`}>
              <div className={styles.col12}>
                <FadeUp>
                  <div className={styles.innerHero}>
                    <h1 className={styles.heroTitle}>
                      AI Systems<br />Built For{" "}
                      <span className={styles.spinnerWindow}>
                        <span
                          className={styles.spinnerReel}
                          style={{
                            height: `${reel.length * 100}%`,
                            transform: `translateY(-${(index * 100) / reel.length}%)`,
                            transition: sliding ? undefined : "none",
                          }}
                        >
                          {reel.map((word, i) => (
                            <span
                              key={i}
                              className={styles.spinnerItem}
                              style={{ height: `${100 / reel.length}%` }}
                            >
                              {word}
                            </span>
                          ))}
                        </span>
                      </span>
                    </h1>

                    <p className={styles.descriptionHero}>
                      We design and ship AI automation, custom software, and growth infrastructure — systems that remove manual work and scale with your team.
                    </p>

                    <div className={styles.buttonGroup}>
                      <Link className={styles.btnDefault} href="#services">
                        Products <ArrowDown size={18} />
                      </Link>
                      <Link className={styles.btnGhost} href="/contact">
                        Contact Us <ArrowRight size={18} />
                      </Link>
                    </div>

                    <p className={styles.heroAnchor}>
                      <b>Meliorate</b> <span className={styles.heroAnchorTag}>(v.)</span> — to make better. Deliberately, in systems that work.
                    </p>
                  </div>
                </FadeUp>
              </div>
            </div>
          </div>
        </div>
      </div>

      <section id="custom-solutions" className={styles.customSolutionsSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.textCenter}>
              <span className={styles.subtitle}>Custom Solutions</span>
              <h2 className={styles.title}>Built Around Your Business</h2>
              <p className={styles.customSolutionsIntro}>
                Beyond products, we architect and deliver custom systems tailored to your goals, workflows,
                and team structure.
              </p>
            </div>
          </FadeUp>

          <Stagger className={styles.solutionGrid} stagger={0.1}>
            {CUSTOM_SOLUTIONS.map((solution) => {
              const Icon = solution.icon;

              return (
                <StaggerItem key={solution.title} className={styles.solutionCard} as="article">
                  <div className={styles.solutionIconWrap}>
                    <Icon size={22} />
                  </div>
                  <h3 className={styles.solutionTitle}>{solution.title}</h3>
                  <p className={styles.solutionDescription}>{solution.description}</p>
                </StaggerItem>
              );
            })}
          </Stagger>

        </div>
      </section>

      <section id="expert" className={styles.expertSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.expertRow}>
              <div className={styles.expertPhotoCol}>
                <div className={styles.expertPhotoWrap}>
                  {/* 1024x1024 is the asset's intrinsic size. The frame has no
                      fixed height, so matching the real 1:1 ratio shows the whole
                      portrait — the old 420x500 would crop a square photo. */}
                  <Image
                    src="/img/adrian.webp"
                    alt="Adrian — AI Automation System Architect"
                    width={1024}
                    height={1024}
                    className={styles.expertPhoto}
                  />
                </div>
              </div>

              <div className={styles.expertTextCol}>
                <h2 className={styles.expertName}>Adrian</h2>
                <p className={styles.expertTitle}>
                  AI Automation System Architect · Consultant · Lecturer &amp; Corporate Education Expert
                </p>

                <div id="adrian-bio">
                  {(bioExpanded ? ADRIAN_BIO : ADRIAN_BIO.slice(0, BIO_PREVIEW)).map((paragraph) => (
                    <p key={paragraph} className={styles.expertBio}>
                      {paragraph}
                    </p>
                  ))}
                </div>

                <button
                  type="button"
                  className={`${styles.bioToggle} ${bioExpanded ? styles.bioToggleOpen : ""}`}
                  onClick={() => setBioExpanded((prev) => !prev)}
                  aria-expanded={bioExpanded}
                  aria-controls="adrian-bio"
                >
                  {bioExpanded ? "Read less" : "Read more"} <ChevronDown size={17} />
                </button>

                <div className={styles.expertTags}>
                  {EXPERT_TAGS.map((tag) => (
                    <span key={tag} className={styles.expertTag}>
                      {tag}
                    </span>
                  ))}
                </div>
                <div className={styles.expertCta}>
                  <Link href="/contact" className={styles.expertCtaLink}>
                    Chat with Adrian <ArrowRight size={18} />
                  </Link>
                </div>
              </div>
            </div>
          </FadeUp>
        </div>
      </section>

      <section id="reviews" className={styles.reviewsSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.textCenter}>
              <span className={styles.subtitle}>Client Reviews</span>
              <h2 className={styles.title}>Trusted by Teams That Execute</h2>
            </div>
          </FadeUp>

          <div className={styles.reviewSliderHead}>
            <span className={styles.googleRating}>5.0 on Google</span>
            <div className={styles.reviewSliderNav}>
              <button
                type="button"
                className={styles.reviewBtn}
                onClick={() => scrollReviews(-1)}
                disabled={!canPrev}
                aria-label="Previous review"
              >
                <ChevronLeft size={19} />
              </button>
              <button
                type="button"
                className={styles.reviewBtn}
                onClick={() => scrollReviews(1)}
                disabled={!canNext}
                aria-label="Next review"
              >
                <ChevronRight size={19} />
              </button>
            </div>
          </div>

          <div className={styles.reviewTrack} ref={reviewTrackRef} onScroll={updateReviewNav}>
            {REVIEWS.map((review) => (
              <article key={review.name} className={styles.reviewSlide}>
                <Quote size={20} className={styles.reviewQuoteIcon} />
                <div className={styles.reviewSlideStars}>
                  {Array.from({ length: 5 }).map((_, idx) => (
                    <Star key={idx} size={14} />
                  ))}
                </div>
                <p className={styles.reviewSlideText}>{review.quote}</p>
                <div className={styles.reviewWho}>
                  <span className={styles.reviewAvatar} aria-hidden="true">
                    <User size={20} />
                  </span>
                  <div>
                    <p className={styles.reviewSlideName}>
                      {review.name}
                      {review.badge && <span className={styles.reviewBadge}>{review.badge}</span>}
                    </p>
                    <p className={styles.reviewSlideRole}>{review.role}</p>
                  </div>
                </div>
              </article>
            ))}
          </div>

          <div className={styles.reviewDots}>
            {REVIEWS.map((review, i) => (
              <button
                key={review.name}
                type="button"
                className={`${styles.reviewDot} ${i === reviewIndex ? styles.reviewDotOn : ""}`}
                onClick={() => goToReview(i)}
                aria-label={`Go to review ${i + 1}`}
              />
            ))}
          </div>
        </div>
      </section>

      <section id="work" className={styles.workSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.workHead}>
              <span className={styles.subtitle}>Selected Work</span>
              <h2 className={styles.title}>Systems We Shipped</h2>
            </div>
          </FadeUp>

          <Stagger className={styles.workGrid} stagger={0.12}>
            {CASE_STUDIES.map((study) => (
              <StaggerItem key={study.slug}>
                <CaseStudyCard study={study} />
              </StaggerItem>
            ))}
          </Stagger>

          <FadeUp delay={0.2}>
            <div className={styles.workCtaWrap}>
              <Link href="/case-studies" className={styles.workCtaLink}>
                All Case Studies <ArrowRight size={18} />
              </Link>
            </div>
          </FadeUp>
        </div>
      </section>

      <section id="services" className={styles.sectionGap}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.textCenter}>
              <span className={styles.subtitle}>Our Ecosystem</span>
              <h2 className={styles.title}>Innovative Products</h2>
            </div>
          </FadeUp>

          <Stagger className={styles.productGrid} stagger={0.12}>
            {PROJECTS.map((project) => {
              const Icon = productIconMap[project.icon];

              return (
                <StaggerItem key={project.slug} className={styles.productCard}>
                  <Link href={project.visitLink} className={styles.productLaunch} target="_blank">
                    Launch <ArrowUpRight size={15} />
                  </Link>
                  <div className={styles.productIcon}>
                    <div className={`${styles.iconInner} ${styles[project.accent]}`}>
                      <Icon size={24} />
                    </div>
                  </div>
                  <h3 className={styles.productName}>{project.name}</h3>
                  <p className={styles.productDescription}>{project.description}</p>
                </StaggerItem>
              );
            })}
          </Stagger>
        </div>
      </section>

      <section id="labs" className={styles.labsSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.labsHead}>
              <span className={styles.subtitle}>Meliorate Labs · Applied Research</span>
              <h2 className={styles.title}>Research You Can Run</h2>
              <p className={styles.labsThesis}>
                Most agent failures in production aren&apos;t model failures — they&apos;re <em>meaning and
                context</em> failures. An agent is only as reliable as the shared model of meaning it reasons
                over, and the context it&apos;s given at the moment it acts.
              </p>
            </div>
          </FadeUp>

          <Stagger className={styles.labsGrid} stagger={0.1}>
            {RESEARCH_THREADS.map((thread) => {
              const Icon = thread.icon;
              return (
                <StaggerItem key={thread.title} className={styles.labsCard} as="article">
                  <div className={styles.labsIcon}>
                    <Icon size={22} />
                  </div>
                  <h3 className={styles.labsCardTitle}>{thread.title}</h3>
                  <p className={styles.labsCardText}>{thread.description}</p>
                </StaggerItem>
              );
            })}
          </Stagger>

        </div>
      </section>

      <section id="high-trust" className={styles.trustSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.trustHead}>
              <span className={styles.subtitle}>Built for High-Trust Work</span>
              <h2 className={styles.title}>Engineered to the Standard Regulated Work Demands</h2>
              <p className={styles.trustIntro}>
                We engineer as though every system will one day face an auditor. What we bring is verifiable
                discipline — memory-safe engineering, security by design, EU data sovereignty, and AI practice
                designed to align with GDPR, the EU AI Act, and ISO/IEC 42001, the management-system standard
                for AI.
              </p>
            </div>
          </FadeUp>

          <Stagger className={styles.trustGrid} stagger={0.08}>
            {TRUST_MARKERS.map((marker) => {
              const Icon = marker.icon;
              return (
                <StaggerItem key={marker.title} className={styles.trustCard} as="article">
                  <div className={styles.trustCardHead}>
                    <span className={styles.trustCardIcon}>
                      <Icon size={20} />
                    </span>
                    <h3 className={styles.trustCardTitle}>{marker.title}</h3>
                  </div>
                  <p className={styles.trustCardText}>{marker.description}</p>
                </StaggerItem>
              );
            })}
          </Stagger>

          <FadeUp delay={0.2}>
            <div className={styles.guardrailChips}>
              {GUARDRAILS.map((g) => (
                <span key={g} className={styles.guardrailChip}>{g}</span>
              ))}
            </div>
          </FadeUp>
        </div>
      </section>

      <section id="announcement" className={styles.announceSection}>
        <div className={styles.container}>
          <FadeUp>
            <div className={styles.announceCard}>
              <span className={styles.announceLogo} aria-hidden="true">
                <Human2HumanLogo size={44} />
              </span>
              <span className={styles.announceEyebrow}>New · Announcement</span>
              <h2 className={styles.announceTitle}>We&apos;ve launched Human2Human</h2>
              <p className={styles.announceText}>
                We teach the same discipline we build on — grounding, context, and human-in-the-loop
                reliability — to European companies and teams, hands-on and in production, aligned with GDPR
                and the EU AI Act. Co-founded by Meliorate Labs and Apriori World.
              </p>
              <div className={styles.announceActions}>
                <Link
                  href="https://human2human.education"
                  target="_blank"
                  rel="noreferrer"
                  className={styles.announceCta}
                >
                  Visit Human2Human <ArrowUpRight size={18} />
                </Link>
              </div>
            </div>
          </FadeUp>
        </div>
      </section>

      <Footer />
    </main>
  );
}
