import React, { useRef } from "react";
import { useLanguage } from "@/hooks/use-language";
import { useLocation } from "wouter";
import { useScrollReveal } from "@/hooks/use-scroll-reveal";

interface FeatureProps {
  icon: string;
  title: string;
  description: string;
  index: number;
  slug: string;
}

const Feature = ({ icon, title, description, index, slug }: FeatureProps) => {
  const [, setLocation] = useLocation();
  const { language } = useLanguage();
  const cardRef = useRef<HTMLElement | null>(null);

  const handleClick = () => {
    setLocation(`/${language}/feature/${slug}`);
  };

  // Cursor-tracking gradient — sets CSS variables that .card-glow reads.
  const handleMove = (e: React.MouseEvent<HTMLElement>) => {
    const el = cardRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    el.style.setProperty("--mx", `${x}%`);
    el.style.setProperty("--my", `${y}%`);
  };

  return (
    <article
      ref={cardRef}
      onMouseMove={handleMove}
      onClick={handleClick}
      itemScope
      itemType="https://schema.org/SoftwareFeature"
      className="card-glow reveal group relative cursor-pointer rounded-2xl border border-neutral-200/70 bg-white p-8 transition-[transform,box-shadow,border-color] duration-500 hover:-translate-y-1 hover:border-primary/30 hover:shadow-[0_30px_60px_-20px_rgba(15,23,42,0.18)]"
    >
      {/* Index marker — adds editorial feel */}
      <div className="absolute top-6 right-6 rtl:right-auto rtl:left-6 font-display text-xs tracking-widest text-neutral-300 group-hover:text-primary/60 transition-colors">
        {String(index + 1).padStart(2, "0")}
      </div>

      <div className="relative mb-6 inline-flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-secondary text-white shadow-lg shadow-primary/20 transition-transform duration-500 group-hover:rotate-[-6deg] group-hover:scale-110">
        {/* Inner gloss */}
        <span
          aria-hidden="true"
          className="pointer-events-none absolute inset-px rounded-[14px]"
          style={{
            background:
              "linear-gradient(135deg, rgba(255,255,255,0.4), transparent 40%)",
          }}
        />
        <i className={`fas ${icon} text-xl relative z-10`} aria-hidden="true" />
      </div>

      <h3
        className="font-display text-xl font-semibold text-neutral-900 mb-3 leading-snug"
        itemProp="name"
      >
        {title}
      </h3>

      <p className="text-neutral-600 leading-relaxed" itemProp="description">
        {description}
      </p>

      {/* Arrow tail revealed on hover */}
      <div className="mt-6 inline-flex items-center gap-2 text-sm font-medium text-primary opacity-0 transition-all duration-300 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0 rtl:translate-x-1 rtl:group-hover:translate-x-0">
        <span>→</span>
      </div>

      <meta itemProp="position" content={(index + 1).toString()} />
    </article>
  );
};

const FeaturesSection = () => {
  const { t, language } = useLanguage();
  const gridRef = useScrollReveal<HTMLDivElement>();
  const headerRef = useScrollReveal<HTMLElement>();

  const features = [
    {
      icon: "fa-calendar-alt",
      title: t("features.appointment.title"),
      description: t("features.appointment.description"),
      slug: language === "ar" ? "جدولة-المواعيد" : "appointment-scheduling",
    },
    {
      icon: "fa-user-md",
      title: t("features.patient.title"),
      description: t("features.patient.description"),
      slug: language === "ar" ? "إدارة-المرضى" : "patient-management",
    },
    {
      icon: "fa-credit-card",
      title: t("features.payment.title"),
      description: t("features.payment.description"),
      slug: language === "ar" ? "معالجة-المدفوعات" : "payment-processing",
    },
    {
      icon: "fa-comments",
      title: t("features.communication.title"),
      description: t("features.communication.description"),
      slug: language === "ar" ? "أدوات-التواصل" : "communication-tools",
    },
    {
      icon: "fa-users-cog",
      title: t("features.access.title"),
      description: t("features.access.description"),
      slug: language === "ar" ? "التحكم-في-الوصول" : "user-access-control",
    },
    {
      icon: "fa-cloud",
      title: t("features.cloud.title"),
      description: t("features.cloud.description"),
      slug: language === "ar" ? "النظام-السحابي" : "cloud-based-system",
    },
    {
      icon: "fa-x-ray",
      title: t("features.xray.title"),
      description: t("features.xray.description"),
      slug: language === "ar" ? "تكامل-الأشعة" : "xray-integration",
    },
    {
      icon: "fa-sms",
      title: t("features.messaging.title"),
      description: t("features.messaging.description"),
      slug: language === "ar" ? "الرسائل-التلقائية" : "sms-whatsapp-messaging",
    },
    {
      icon: "fa-cloud-upload-alt",
      title: t("features.aws.title"),
      description: t("features.aws.description"),
      slug: language === "ar" ? "خدمات-aws" : "aws-cloud-services",
    },
    {
      icon: "fa-shield-alt",
      title: t("features.hipaa.title"),
      description: t("features.hipaa.description"),
      slug: language === "ar" ? "امتثال-hipaa" : "hipaa-compliance",
    },
    {
      icon: "fa-tooth",
      title: t("features.treatmentPlan.title"),
      description: t("features.treatmentPlan.description"),
      slug:
        language === "ar" ? "تخطيط-العلاج-السنى" : "dental-treatment-planning",
    },
  ];

  return (
    <section
      className="relative py-24 bg-gray-50 overflow-hidden"
      itemScope
      itemType="https://schema.org/SoftwareApplication"
    >
      {/* Decorative blurred orbs */}
      <div
        aria-hidden="true"
        className="absolute -top-20 left-1/4 h-72 w-72 rounded-full opacity-25 blur-3xl"
        style={{ background: "hsl(315 70% 55% / 0.35)" }}
      />
      <div
        aria-hidden="true"
        className="absolute bottom-0 right-1/4 h-80 w-80 rounded-full opacity-25 blur-3xl"
        style={{ background: "hsl(197 90% 55% / 0.35)" }}
      />

      <div className="relative container mx-auto px-4">
        <header
          ref={headerRef}
          className="text-center mb-16 reveal max-w-3xl mx-auto"
        >
          <div className="inline-block text-xs uppercase tracking-[0.2em] text-primary/80 font-semibold mb-4">
            {t("features.eyebrow") !== "features.eyebrow"
              ? t("features.eyebrow")
              : language === "ar"
                ? "الإمكانيات"
                : "Capabilities"}
          </div>
          <h2
            className="font-display text-4xl md:text-5xl font-semibold text-neutral-900 mb-5 leading-tight"
            itemProp="name"
          >
            {t("features.title")}
          </h2>
          <p className="text-lg text-neutral-600" itemProp="description">
            {t("features.subtitle")}
          </p>
        </header>

        <div
          ref={gridRef}
          className="stagger grid md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8"
          itemProp="featureList"
          itemScope
          itemType="https://schema.org/ItemList"
        >
          {features.map((feature, index) => (
            <Feature
              key={index}
              icon={feature.icon}
              title={feature.title}
              description={feature.description}
              index={index}
              slug={feature.slug}
            />
          ))}
        </div>

        {/* Structured Data for SEO */}
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "SoftwareApplication",
              name: t("features.title"),
              description: t("features.subtitle"),
              applicationCategory: "HealthcareSoftware",
              operatingSystem: "Web",
              offers: {
                "@type": "Offer",
                category: "Clinic Management System",
              },
              featureList: features.map((feature, index) => ({
                "@type": "SoftwareFeature",
                name: feature.title,
                description: feature.description,
                position: index + 1,
              })),
              keywords: [
                "clinic management system",
                "dental clinic software",
                "medical practice management",
                "appointment scheduling",
                "patient management",
                "HIPAA compliant",
                "AWS cloud services",
                "X-ray integration",
                "SMS WhatsApp messaging",
                "treatment planning",
              ],
            }),
          }}
        />
      </div>
    </section>
  );
};

export default FeaturesSection;
