import { createFileRoute, notFound, Link } from "@tanstack/react-router";
import { CheckCircle2, ArrowRight } from "lucide-react";
import { SiteLayout } from "@/components/site/Layout";
import { PageHero } from "@/components/site/PageHero";
import { Section, SectionHeader } from "@/components/site/Section";
import { CTAButtons } from "@/components/site/CTAButtons";
import { FAQ } from "@/components/site/FAQ";
import { Testimonials } from "@/components/site/Testimonials";
import { ContactForm } from "@/components/site/ContactForm";
import { JsonLd } from "@/components/site/JsonLd";
import { SERVICES, SITE, FAQ as FAQ_DATA } from "@/lib/site";

type ServiceContent = {
  longTitle: string;
  intro: string;
  includes: string[];
  process: { title: string; text: string }[];
  keywords: string[];
  faq?: { q: string; a: string }[];
};

const CONTENT: Record<string, ServiceContent> = {
  "wordpress-malware-removal": {
    longTitle: "WordPress Malware Removal Service",
    intro: "Your WordPress site is infected with malware, redirects, spam links, or pharma SEO injections? We do a deep, surgical clean — every PHP file, the database, cron jobs, and user accounts — then harden the site so it doesn't come back.",
    includes: [
      "Full file system & database malware scan",
      "Manual removal of injected code (no plugin-only cleanup)",
      "Backdoor & rogue admin user removal",
      "Cron job and .htaccess audit",
      "Removal from Google Safe Browsing blacklist",
      "30-day clean guarantee + post-clean hardening",
    ],
    process: [
      { title: "Diagnose", text: "We scan files, DB, and server logs to map every infection." },
      { title: "Remove", text: "Manual surgical clean — preserving your content, removing only malicious code." },
      { title: "Harden", text: "Strong passwords, file permissions, security headers, login protection." },
      { title: "Monitor", text: "30 days of follow-up scans included to confirm the site stays clean." },
    ],
    keywords: ["wordpress malware removal", "remove malware from wordpress", "wordpress virus removal"],
  },
  "fix-hacked-wordpress-site": {
    longTitle: "Fix Hacked WordPress Site — Full Recovery",
    intro: "Site defaced? Redirecting to spam? Locked out of admin? Don't panic. We've recovered 100+ hacked WordPress sites with zero data loss and full SEO retention.",
    includes: [
      "Emergency 24/7 response (within 30 minutes)",
      "Full site recovery — even with no working backup",
      "Hack vector analysis (we tell you HOW it happened)",
      "Plugin & theme audit and replacement",
      "Google Search Console deindex/blacklist removal",
      "Post-recovery monitoring & 30-day guarantee",
    ],
    process: [
      { title: "Stabilize", text: "Lock down the site to stop further damage and re-infection." },
      { title: "Recover", text: "Restore from clean state, preserving content, posts, and users." },
      { title: "Investigate", text: "Find and patch the entry point so it cannot happen again." },
      { title: "Restore SEO", text: "Submit clean URLs to Google, remove warnings, rebuild trust." },
    ],
    keywords: ["fix hacked wordpress site", "wordpress hacked recovery", "wordpress site hacked help"],
  },
  "wordpress-bug-fixing": {
    longTitle: "WordPress Bug Fixing Service",
    intro: "White screen of death, 500 errors, plugin conflicts, broken admin, fatal PHP errors — pick any. We diagnose the root cause and fix it cleanly, no bandaids.",
    includes: [
      "PHP error & debug log analysis",
      "Plugin & theme conflict resolution",
      "Database query and option table cleanup",
      "Broken page builder fixes (Elementor, Divi, WPBakery)",
      "Multisite / WPML / RTL fixes",
      "14-day fix guarantee",
    ],
    process: [
      { title: "Reproduce", text: "We replicate the issue in a safe staging copy first." },
      { title: "Isolate", text: "Binary-search through plugins, themes, and core to find the culprit." },
      { title: "Fix", text: "Apply a clean, maintainable fix — no commented-out hacks." },
      { title: "Test", text: "Front-end + admin + checkout flow verified before delivery." },
    ],
    keywords: ["wordpress bug fixing", "wordpress error fix", "wordpress white screen fix"],
  },
  "woocommerce-fixes": {
    longTitle: "WooCommerce Error & Issue Fix",
    intro: "Cart not working? Razorpay or Stripe failing? Tax / shipping / variation bugs? Lost orders kill stores — we fix WooCommerce issues fast so you stop bleeding revenue.",
    includes: [
      "Cart, checkout & payment gateway debugging",
      "Razorpay, Stripe, PayPal, PayU integration fixes",
      "Tax, shipping zones, variation pricing fixes",
      "Order email & receipt repair",
      "Subscription & membership plugin issues",
      "Product import/export & migration support",
    ],
    process: [
      { title: "Audit", text: "Walk the full purchase flow with you to identify break points." },
      { title: "Fix", text: "Patch the gateway, plugin, or theme conflict at root." },
      { title: "Verify", text: "Run real test transactions end-to-end before sign-off." },
      { title: "Document", text: "Tell you what failed so it stays fixed." },
    ],
    keywords: ["woocommerce error fix", "woocommerce payment fix", "woocommerce expert"],
  },
  "wordpress-speed-optimization": {
    longTitle: "WordPress Speed Optimization Service",
    intro: "Slow site = lost traffic and lost sales. We get you to 90+ on Google PageSpeed and Core Web Vitals — no shady plugins, no broken layouts.",
    includes: [
      "Image optimization (WebP, lazy loading, responsive)",
      "Critical CSS, JS deferral, render-blocking removal",
      "Database optimization & cleanup",
      "Caching layer setup (LiteSpeed, WP Rocket, Redis)",
      "CDN configuration (Cloudflare, BunnyCDN)",
      "Before/after PageSpeed report",
    ],
    process: [
      { title: "Benchmark", text: "Document current scores: PageSpeed, GTmetrix, Web Vitals." },
      { title: "Optimize", text: "Apply 30+ proven optimizations specific to your stack." },
      { title: "Validate", text: "Re-test on real devices, mobile and desktop." },
      { title: "Report", text: "Send a before/after summary with proof." },
    ],
    keywords: ["wordpress speed optimization", "wordpress speed expert", "make wordpress faster"],
  },
  "monthly-wordpress-maintenance": {
    longTitle: "Monthly WordPress Maintenance & Care",
    intro: "Stop worrying about your site. Monthly care plan covers backups, updates, security scans, uptime monitoring, and 30 minutes of changes per month.",
    includes: [
      "Weekly off-site backups (Dropbox/Google Drive)",
      "Plugin, theme & core updates with regression checks",
      "Daily malware & uptime monitoring",
      "Monthly performance & security audit",
      "30 minutes of small changes / edits per month",
      "Priority support (response within 1 hour)",
    ],
    process: [
      { title: "Onboard", text: "Initial audit + harden + baseline snapshot." },
      { title: "Maintain", text: "Weekly updates and backups, automated monitoring." },
      { title: "Report", text: "Monthly summary email with everything done." },
      { title: "Respond", text: "Priority queue for any emergencies that month." },
    ],
    keywords: ["wordpress maintenance plan", "wordpress care plan", "monthly wordpress support"],
  },
  "website-redesign-minor-changes": {
    longTitle: "WordPress Redesign & Minor Changes",
    intro: "Need a quick text edit, a logo swap, mobile menu fix, or a fresh new look? Whether it's a 10-minute tweak or a full redesign, we ship clean and fast.",
    includes: [
      "Text, image, and content edits",
      "CSS / design tweaks & polishing",
      "Mobile responsiveness fixes",
      "New section / page builds (Elementor, Divi, Gutenberg)",
      "Logo & branding updates",
      "Full site redesign (separate quote)",
    ],
    process: [
      { title: "Brief", text: "Send a screenshot or quick description — we'll quote it." },
      { title: "Build", text: "Work in staging or directly on a copy." },
      { title: "Review", text: "You approve before anything goes live." },
      { title: "Ship", text: "Push live, verify across devices." },
    ],
    keywords: ["wordpress design fix", "wordpress edit", "wordpress small changes"],
  },
};

export const Route = createFileRoute("/services/$slug")({
  loader: ({ params }) => {
    const service = SERVICES.find((s) => s.slug === params.slug);
    const content = CONTENT[params.slug];
    if (!service || !content) throw notFound();
    return { service, content };
  },
  head: ({ loaderData }) => {
    if (!loaderData) return {};
    const { service, content } = loaderData;
    const title = `${content.longTitle} — ${SITE.name}`;
    const desc = content.intro.slice(0, 158);
    return {
      meta: [
        { title },
        { name: "description", content: desc },
        { name: "keywords", content: content.keywords.join(", ") },
        { property: "og:title", content: content.longTitle },
        { property: "og:description", content: desc },
      ],
      links: [{ rel: "canonical", href: `${SITE.url}/services/${service.slug}` }],
    };
  },
  component: ServiceDetailPage,
});

function ServiceDetailPage() {
  const { service, content } = Route.useLoaderData();

  const faqItems = content.faq && content.faq.length > 0 ? content.faq : FAQ_DATA;
  const serviceSchema = {
    "@context": "https://schema.org",
    "@type": "Service",
    name: content.longTitle,
    serviceType: service.title,
    description: content.intro,
    url: `${SITE.url}/services/${service.slug}`,
    provider: {
      "@type": "ProfessionalService",
      name: SITE.legalName,
      url: SITE.url,
      email: SITE.email,
      telephone: SITE.phone,
    },
    areaServed: { "@type": "Place", name: "Worldwide" },
    hasOfferCatalog: {
      "@type": "OfferCatalog",
      name: content.longTitle,
      itemListElement: content.includes.map((item: string) => ({
        "@type": "Offer",
        itemOffered: { "@type": "Service", name: item },
      })),
    },
    offers: {
      "@type": "Offer",
      price: service.price.replace(/[^\d]/g, ""),
      priceCurrency: "INR",
      availability: "https://schema.org/InStock",
      url: `${SITE.url}/services/${service.slug}`,
    },
    aggregateRating: {
      "@type": "AggregateRating",
      ratingValue: "4.9",
      reviewCount: "100",
      bestRating: "5",
      worstRating: "1",
    },
  };
  const faqSchema = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: faqItems.map((f: { q: string; a: string }) => ({
      "@type": "Question",
      name: f.q,
      acceptedAnswer: { "@type": "Answer", text: f.a },
    })),
  };
  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      { "@type": "ListItem", position: 1, name: "Home", item: SITE.url },
      { "@type": "ListItem", position: 2, name: "Services", item: `${SITE.url}/services` },
      { "@type": "ListItem", position: 3, name: service.title, item: `${SITE.url}/services/${service.slug}` },
    ],
  };

  return (
    <SiteLayout>
      <JsonLd data={serviceSchema} />
      <JsonLd data={faqSchema} />
      <JsonLd data={breadcrumbSchema} />
      <PageHero eyebrow="Service" title={content.longTitle} subtitle={content.intro}>
        <div className="flex flex-wrap items-center gap-4">
          <CTAButtons />
          <div className="rounded-lg bg-cream/10 border border-cream/20 px-4 py-3 text-cream">
            <span className="text-xs uppercase tracking-wider opacity-75">Starts at</span>
            <div className="font-display text-2xl font-bold">{service.price} <span className="text-sm font-normal opacity-75">/ {service.priceUSD}</span></div>
          </div>
        </div>
      </PageHero>

      <Section>
        <div className="grid lg:grid-cols-5 gap-12">
          <div className="lg:col-span-3">
            <h2 className="text-3xl font-bold">What's included</h2>
            <ul className="mt-6 space-y-3">
              {content.includes.map((item: string) => (
                <li key={item} className="flex gap-3">
                  <CheckCircle2 className="h-5 w-5 text-emerald flex-shrink-0 mt-0.5" />
                  <span>{item}</span>
                </li>
              ))}
            </ul>
            <h2 className="mt-12 text-3xl font-bold">Our process</h2>
            <div className="mt-6 grid sm:grid-cols-2 gap-5">
              {content.process.map((p: { title: string; text: string }, i: number) => (
                <div key={p.title} className="rounded-xl border border-border bg-card p-5 shadow-soft">
                  <div className="font-display text-emerald font-bold">Step {i + 1}</div>
                  <h3 className="mt-1 font-semibold">{p.title}</h3>
                  <p className="mt-2 text-sm text-muted-foreground">{p.text}</p>
                </div>
              ))}
            </div>
          </div>

          <aside className="lg:col-span-2">
            <div className="sticky top-24 rounded-2xl bg-gradient-hero text-cream p-7 shadow-elegant">
              <h3 className="font-display text-xl font-bold">Get this fixed today</h3>
              <p className="mt-2 text-cream/80 text-sm">Reply within 30 minutes. Money-back if we can't fix it.</p>
              <div className="mt-5 space-y-3">
                <Link to="/contact" className="block w-full text-center rounded-lg bg-gradient-emerald px-5 py-3 font-semibold text-navy-deep">
                  Request This Fix
                </Link>
                <Link to="/pricing" className="block w-full text-center rounded-lg border border-cream/25 px-5 py-3 font-semibold hover:bg-cream/5">
                  View All Pricing
                </Link>
              </div>
              <div className="mt-6 pt-6 border-t border-cream/15 text-sm space-y-1 text-cream/80">
                <div>✓ 14-day fix guarantee</div>
                <div>✓ Same-day delivery available</div>
                <div>✓ Clean code — no hacks</div>
              </div>
            </div>
          </aside>
        </div>
      </Section>

      <Section bg="muted">
        <SectionHeader eyebrow="More Services" title="Other ways we help" />
        <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          {SERVICES.filter((s) => s.slug !== service.slug).slice(0, 3).map((s) => (
            <Link
              key={s.slug}
              to="/services/$slug"
              params={{ slug: s.slug }}
              className="group rounded-2xl border border-border bg-card p-6 shadow-soft hover:shadow-elegant transition-all"
            >
              <h3 className="font-semibold">{s.title}</h3>
              <p className="mt-2 text-sm text-muted-foreground">{s.short}</p>
              <span className="mt-4 inline-flex items-center gap-1 text-sm font-medium text-emerald group-hover:gap-2 transition-all">
                Learn more <ArrowRight className="h-4 w-4" />
              </span>
            </Link>
          ))}
        </div>
      </Section>

      <Section>
        <SectionHeader eyebrow="FAQ" title="Common questions" />
        <FAQ />
      </Section>

      <Section bg="muted">
        <SectionHeader eyebrow="Reviews" title="What clients say" />
        <Testimonials />
      </Section>

      <Section>
        <div className="grid gap-12 lg:grid-cols-2 items-start">
          <div>
            <SectionHeader align="left" eyebrow="Get started" title={`Request your ${service.title.toLowerCase()}`} subtitle="Describe your issue. We reply with a quote within 30 minutes." />
          </div>
          <ContactForm />
        </div>
      </Section>
    </SiteLayout>
  );
}
