"use client";
import React, { useEffect, useRef, useState } from "react";
import Layoutreact from "@/components/layout/layout";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import styles from "./description.module.css";

// Custom hook to detect WebP support
const useWebPSupport = () => {
  const [supportsWebP, setSupportsWebP] = useState<boolean | null>(null);

  useEffect(() => {
    const checkWebPSupport = () => {
      const canvas = document.createElement("canvas");
      canvas.width = 1;
      canvas.height = 1;
      const ctx = canvas.getContext("2d");

      if (ctx) {
        const dataURL = canvas.toDataURL("image/webp");
        const supportsWebP = dataURL.indexOf("data:image/webp") === 0;
        setSupportsWebP(supportsWebP);
      } else {
        setSupportsWebP(false);
      }
    };

    checkWebPSupport();
  }, []);

  return supportsWebP;
};

const sections = [
  {
    title: "Description",
    content: [
      {
        text: "The Guard web application is built with modern, reliable technologies to ensure a fast and seamless user experience. Powered by <strong>Next.js 15</strong> and styled with <strong>Tailwind CSS</strong>, it uses <strong>TypeScript</strong> for robust type safety and <strong>Prisma ORM</strong> for efficient communication with a <strong>PostgreSQL</strong> database. Secure authentication is provided through <strong>NextAuth</strong>, supporting both <strong>JWT</strong> and <strong>Google OAuth</strong> logins.",
        strong: false,
        useHtml: true,
      },
      {
        text: "Behind the scenes, Guard leverages two powerful context providers:",
        strong: false,
      },
      {
        text: "AuthProvider:",
        strong: true,
        isListItem: true,
        description:
          "This manages authentication using server-side session checks with <strong>JWT</strong> tokens, automatically refreshing sessions when needed for continuous security.",
        useHtml: true,
      },
      {
        text: "DashboardDataProvider:",
        strong: true,
        isListItem: true,
        description:
          "Using a custom hook, this keeps all dashboard data and state centralized in one place, making the user experience smooth and responsive.",
      },
      {
        text: "Most backend features are powered by <strong>Next.js server actions</strong> and a set of secure API endpoints. In addition, there&apos;s a dedicated <strong>Express.js</strong> (<strong>Node.js</strong>) API endpoint designed to handle requests from remote Windows client devices. This ensures the Guard web app and client apps work independently and reliably, even in complex environments.",
        strong: false,
        useHtml: true,
      },
    ],
    imageUrl: "/description/8-min",
  },
];

export default function WebappDescriptionPage() {
  const sectionRefs = useRef<(HTMLElement | null)[]>([]);
  const supportsWebP = useWebPSupport();

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add(styles.visible);
          }
        });
      },
      {
        threshold: 0.3,
        rootMargin: "50px 0px -10% 0px",
      }
    );

    sectionRefs.current.forEach((ref, index) => {
      if (ref) {
        // Make first section visible immediately
        if (index === 0) {
          ref.classList.add(styles.visible);
        }
        observer.observe(ref);
      }
    });

    return () => {
      sectionRefs.current.forEach((ref) => {
        if (ref) {
          observer.unobserve(ref);
        }
      });
    };
  }, []);

  return (
    <Layoutreact>
      {/* Back Button */}
      <div className="container mx-auto px-4 pt-8 pb-4">
        <Button asChild variant="outline" className="gap-2">
          <Link href="/info">
            <ArrowLeft className="w-4 h-4" />
            Back to Project Info
          </Link>
        </Button>
      </div>

      {/* Compact Header */}
      <header className="border-b bg-background/80 backdrop-blur-sm sticky top-0 z-50">
        <div className="container mx-auto px-4 py-4">
          <div className="flex justify-center">
            <h1 className="text-lg sm:text-xl md:text-2xl font-bold hero-text-gradient">
              Web Platform - Technical Overview
            </h1>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto mb-8">
          <p className="text-center text-muted-foreground text-lg">
            An overview of the Guard web platform&apos;s modern technology stack
            and architecture, designed to provide reliable parental control
            capabilities.
          </p>
        </div>

        {sections.map((section, index) => (
          <section
            key={index}
            ref={(el) => {
              sectionRefs.current[index] = el;
            }}
            className={`${styles.descriptionSection} ${
              index % 2 === 0 ? styles.slideInRight : styles.slideInLeft
            }`}
          >
            <div className={styles.contentWrapper}>
              <div className={styles.textContent}>
                <h2 className="hero-text-gradient">{section.title}</h2>
                {section.content.map((item, itemIndex) =>
                  item.isListItem ? (
                    <div key={itemIndex} className={styles.listItem}>
                      <strong>{item.text}</strong>{" "}
                      {item.useHtml ? (
                        <span
                          dangerouslySetInnerHTML={{ __html: item.description }}
                        />
                      ) : (
                        item.description
                      )}
                    </div>
                  ) : (
                    <p
                      key={itemIndex}
                      className={
                        "isContinuation" in item && item.isContinuation
                          ? "mt-4"
                          : ""
                      }
                    >
                      {item.useHtml ? (
                        <span dangerouslySetInnerHTML={{ __html: item.text }} />
                      ) : (
                        item.text
                      )}
                    </p>
                  )
                )}
              </div>
              <div className={styles.imageContent}>
                <Image
                  src={
                    supportsWebP === null
                      ? section.imageUrl
                      : supportsWebP
                      ? `${section.imageUrl}.webp`
                      : `${section.imageUrl}.png`
                  }
                  alt={`Illustration for ${section.title}`}
                  width={500}
                  height={350}
                  className="rounded-lg border-12 shadow-lg"
                />
              </div>
            </div>
          </section>
        ))}
      </main>
    </Layoutreact>
  );
}
