import { useEffect, useState } from "react";
import SiteLayout from "@/components/SiteLayout";
import AnimateIn from "@/components/AnimateIn";
import { ContactUsModal, GetPriceModal } from "@/components/ContactModals";
import PresalesChatWidget from "@/components/PresalesChatWidget";
import {
  Mail,
  ShieldCheck,
  Lock,
  Bug,
  Inbox,
  CalendarDays,
  Smartphone,
  Monitor,
  Users,
  FileText,
  FolderOpen,
  Archive,
  ServerCog,
  ArrowRight,
  Check,
  Sparkles,
  BadgeCheck,
  Clock,
  Headphones,
  Globe,
  ChevronDown,
  Loader2,
} from "lucide-react";

/**
 * Bizmail360 — Collaboration Mail System
 * ---------------------------------------
 * DoItEasy-branded marketing page for our business email & collaboration
 * platform (Bizmail360). Mirrors the structure/content of the reference
 * page without copying its source — recreated in our React + shadcn/ui +
 * Tailwind stack with the DoItEasy palette (green #0e6305, dark #1e3828).
 *
 * Pricing plans are pulled from the backend `plans` table filtered by
 * `service_type = "bizmail360"`; a small static fallback is shown while
 * loading or if the API is not reachable.
 */

// --------------------------- Static content --------------------------------

const keyFeatures = [
  {
    icon: Mail,
    title: "Business Email Hosting",
    desc: "Professional email on your own custom domain (you@yourcompany.com) with blazing-fast IMAP, POP3 and SMTP servers tuned for deliverability.",
  },
  {
    icon: ShieldCheck,
    title: "Advanced Anti-Spam & Anti-Phishing",
    desc: "Multi-layer filtering, reputation scoring, URL rewriting and real-time phishing detection block 99.9% of junk before it reaches the inbox.",
  },
  {
    icon: Bug,
    title: "Anti-Virus & Malware Protection",
    desc: "Every inbound and outbound attachment is scanned in real time against multiple AV engines, including zero-day sandbox detonation.",
  },
  {
    icon: Lock,
    title: "Email Encryption (TLS/SSL)",
    desc: "End-to-end TLS 1.3 in transit, encrypted storage at rest and opportunistic S/MIME support for sensitive communications.",
  },
  {
    icon: Inbox,
    title: "Large Mailboxes & Attachments",
    desc: "Generous per-user mailbox quotas (up to 100 GB+) and attachments up to 50 MB — no awkward size limits blocking your team.",
  },
  {
    icon: CalendarDays,
    title: "Shared Calendars & Contacts",
    desc: "Team calendars, resource booking and shared address books keep everyone aligned without switching apps.",
  },
  {
    icon: Smartphone,
    title: "Mobile & Desktop Sync",
    desc: "Native IMAP / POP / ActiveSync / CalDAV / CardDAV — works seamlessly with Outlook, Apple Mail, Thunderbird, Gmail and mobile.",
  },
  {
    icon: Monitor,
    title: "Modern Webmail UI",
    desc: "Fast, responsive webmail with dark mode, rich-text composer, keyboard shortcuts, rules, filters and labels — right from the browser.",
  },
];

const collabTools = [
  {
    icon: Mail,
    title: "Business Mail",
    desc: "Professional inboxes on your own domain with shared mailboxes, aliases and delegated access.",
  },
  {
    icon: Users,
    title: "Team Chat",
    desc: "Real-time channels, direct messages, file sharing and searchable history — built into the workspace.",
  },
  {
    icon: Monitor,
    title: "Video Meetings",
    desc: "HD video meetings with screen share, recordings and one-click join from mail & chat.",
  },
  {
    icon: FileText,
    title: "Docs & Drive",
    desc: "Real-time co-editing of docs, sheets and slides with shared drives and version history.",
  },
  {
    icon: CalendarDays,
    title: "Shared Calendars",
    desc: "Overlay team calendars, free/busy lookup and meeting invites with reminders.",
  },
  {
    icon: FolderOpen,
    title: "Team Folders",
    desc: "Shared mailboxes and folders for support@, sales@ or project-based collaboration.",
  },
];

const securityItems = [
  { icon: BadgeCheck, label: "DKIM / SPF / DMARC" },
  { icon: Lock, label: "TLS 1.3 Encryption" },
  { icon: ShieldCheck, label: "Spam Quarantine" },
  { icon: Bug, label: "Virus & Malware Scanning" },
  { icon: Archive, label: "Backup & Archiving" },
  { icon: ServerCog, label: "Admin Policies & Audit Logs" },
];

const whyPoints = [
  {
    icon: Sparkles,
    title: "Built For Business",
    desc: "Purpose-built stack — not a consumer service — with SLA, uptime reports and business-grade deliverability.",
  },
  {
    icon: Clock,
    title: "99.9% Uptime SLA",
    desc: "Redundant mail clusters, geo-distributed storage and automated failover keep your email always on.",
  },
  {
    icon: Globe,
    title: "Hosted by DoItEasy",
    desc: "Local support, local billing, local data-center options — backed by DoItEasy's full hosting platform.",
  },
  {
    icon: Headphones,
    title: "24/7 Expert Support",
    desc: "Certified email engineers available around the clock via ticket, chat or phone.",
  },
];

const faqs = [
  {
    q: "What is Bizmail360?",
    a: "Bizmail360 is DoItEasy's business-grade collaboration mail system. It combines professional email hosting on your custom domain with advanced security (anti-spam, anti-phishing, anti-virus, TLS encryption) and team collaboration tools like shared calendars, contacts, tasks and team folders.",
  },
  {
    q: "Can you migrate my existing email from Google Workspace, Microsoft 365 or cPanel?",
    a: "Yes. Our migration team performs zero-downtime migrations using IMAP sync tools for mail, plus calendar/contact imports. Standard migrations are included with Business and Enterprise plans; we'll schedule the cutover at a time that works for your business.",
  },
  {
    q: "Which mail clients and devices are supported?",
    a: "Everything standards-based: Outlook (Windows/Mac), Apple Mail, Thunderbird, iOS Mail, Android, Gmail app and any IMAP/POP/ActiveSync client. Calendars and contacts sync via CalDAV/CardDAV or ActiveSync, so they show up natively on every device.",
  },
  {
    q: "How secure is Bizmail360?",
    a: "Every connection is protected with TLS 1.3 in transit, data at rest is encrypted, and we enforce DKIM, SPF and DMARC for your domain. Inbound mail is scanned by multi-engine anti-spam, anti-phishing and anti-virus filters with quarantine and admin review.",
  },
  {
    q: "How much mailbox storage do I get?",
    a: "Starter plans start at 10 GB per mailbox, Business plans include 50 GB per mailbox with full collaboration, and Enterprise plans offer 100 GB+ per mailbox plus archiving and compliance retention. All quotas can be upgraded at any time.",
  },
  {
    q: "How is Bizmail360 priced?",
    a: "Plans are billed per mailbox per month with annual discounts available. Starter is ideal for small teams, Business is our most popular plan for growing companies, and Enterprise covers large organisations with SLA and dedicated support. Contact sales for volume pricing.",
  },
];

// -------------------------- Plan types / fetching --------------------------

interface BackendPlan {
  id?: number;
  service_type?: string;
  name: string;
  price: number;
  currency?: string | null;
  billing_cycle?: string | null;
  features?: string | null;
  cta_label?: string | null;
  cta_url?: string | null;
  is_featured?: boolean | null;
  is_active?: boolean | null;
  sort_order?: number | null;
  tagline?: string | null;
}

const FALLBACK_PLANS: BackendPlan[] = [
  {
    name: "Starter",
    price: 3,
    currency: "USD",
    billing_cycle: "/mailbox/month",
    tagline: "Small teams just getting started",
    features: JSON.stringify([
      "10 GB mailbox per user",
      "Anti-spam & anti-phishing",
      "Modern webmail access",
      "IMAP / POP / mobile sync",
      "Email support",
    ]),
    is_featured: false,
    sort_order: 1,
    cta_label: "Get Started",
  },
  {
    name: "Business",
    price: 6,
    currency: "USD",
    billing_cycle: "/mailbox/month",
    tagline: "Most popular ✦ For growing companies",
    features: JSON.stringify([
      "50 GB mailbox per user",
      "Shared calendars, contacts & tasks",
      "Team folders & shared mailboxes",
      "Advanced security & encryption",
      "Priority support",
    ]),
    is_featured: true,
    sort_order: 2,
    cta_label: "Try Business",
  },
  {
    name: "Enterprise",
    price: 12,
    currency: "USD",
    billing_cycle: "/mailbox/month",
    tagline: "Large organisations with compliance needs",
    features: JSON.stringify([
      "100 GB+ mailbox per user",
      "Email archiving & retention",
      "Compliance & audit logs",
      "Dedicated account manager",
      "99.9% uptime SLA",
    ]),
    is_featured: false,
    sort_order: 3,
    cta_label: "Contact Sales",
  },
];

function parseFeatures(raw: string | null | undefined): string[] {
  if (!raw) return [];
  // Try JSON first, fall back to newline / comma split.
  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) return parsed.map((x) => String(x));
  } catch {
    // not JSON
  }
  return raw
    .split(/\r?\n|,/)
    .map((s) => s.trim())
    .filter(Boolean);
}

async function fetchBizmailPlans(): Promise<BackendPlan[]> {
  const candidates = [
    `/api/v1/entities/plans?query=${encodeURIComponent(
      JSON.stringify({ service_type: "bizmail360", is_active: true }),
    )}&sort=sort_order&limit=20`,
    `/api/v1/entities/plans?query=${encodeURIComponent(
      JSON.stringify({ service_type: "bizmail360" }),
    )}&sort=sort_order&limit=20`,
    "/api/v1/entities/plans?limit=50",
  ];
  for (const url of candidates) {
    try {
      const res = await fetch(url, { headers: { Accept: "application/json" } });
      if (!res.ok) continue;
      const data = await res.json();
      const list: BackendPlan[] = Array.isArray(data)
        ? data
        : Array.isArray(data?.items)
          ? data.items
          : Array.isArray(data?.data)
            ? data.data
            : [];
      const filtered = list.filter(
        (p) => !p.service_type || p.service_type === "bizmail360",
      );
      if (filtered.length > 0) return filtered;
    } catch {
      // try next URL
    }
  }
  return [];
}

// -------------------------------- Page -------------------------------------

export default function Bizmail360() {
  const [priceOpen, setPriceOpen] = useState(false);
  const [contactOpen, setContactOpen] = useState(false);
  const [plans, setPlans] = useState<BackendPlan[]>(FALLBACK_PLANS);
  const [loadingPlans, setLoadingPlans] = useState(true);
  const [openFaq, setOpenFaq] = useState<number | null>(0);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const result = await fetchBizmailPlans();
      if (cancelled) return;
      if (result.length > 0) {
        // Sort by sort_order if present
        const sorted = [...result].sort(
          (a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0),
        );
        setPlans(sorted);
      }
      setLoadingPlans(false);
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const scrollToPlans = () => {
    document.getElementById("plans")?.scrollIntoView({ behavior: "smooth" });
  };

  return (
    <SiteLayout>
      {/* HERO ---------------------------------------------------------- */}
      <section className="relative overflow-hidden bg-[#0b1d14] text-white">
        <div className="absolute inset-0 -z-0">
          <div className="absolute inset-0 bg-gradient-to-br from-[#0b1d14] via-[#123826] to-[#0e6305]" />
          <div className="absolute -top-40 -right-32 w-[40rem] h-[40rem] rounded-full bg-[#0e6305]/40 blur-3xl" />
          <div className="absolute -bottom-40 -left-32 w-[40rem] h-[40rem] rounded-full bg-emerald-400/10 blur-3xl" />
          <div
            className="absolute inset-0 opacity-[0.15]"
            style={{
              backgroundImage:
                "radial-gradient(rgba(255,255,255,0.4) 1px, transparent 1px)",
              backgroundSize: "24px 24px",
            }}
          />
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-32 pb-24">
          <div className="grid lg:grid-cols-2 gap-12 items-center">
            <AnimateIn direction="right">
              <div className="inline-flex items-center gap-2 bg-emerald-400/15 border border-emerald-400/40 backdrop-blur-sm rounded-full px-4 py-1.5 text-xs md:text-sm mb-5">
                <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
                Bizmail360 · Secure Business Email
              </div>

              <h1 className="text-4xl md:text-5xl lg:text-6xl font-extrabold leading-tight mb-5">
                Bizmail360 —{" "}
                <span className="text-emerald-300">
                  Collaboration Mail System
                </span>
              </h1>
              <p className="text-lg md:text-xl text-slate-200 mb-8 leading-relaxed max-w-xl">
                One secure workspace for <strong>mail, chat, meetings &amp; docs</strong>
                {" "}— hosted by DoItEasy, on your own domain, with enterprise-grade
                security and 24/7 expert support.
              </p>

              <div className="flex flex-wrap gap-3">
                <button
                  type="button"
                  onClick={() => setPriceOpen(true)}
                  className="px-7 py-3.5 rounded-md bg-[#f5c400] text-[#1e3828] font-bold hover:bg-yellow-400 transition shadow-2xl shadow-yellow-500/20 inline-flex items-center gap-2"
                >
                  <Mail className="w-5 h-5" /> Get Started
                </button>
                <button
                  type="button"
                  onClick={() => setContactOpen(true)}
                  className="px-7 py-3.5 rounded-md bg-white/10 border border-white/25 text-white font-bold hover:bg-white/20 transition backdrop-blur-sm inline-flex items-center gap-2"
                >
                  Contact Sales <ArrowRight className="w-4 h-4" />
                </button>
                <button
                  type="button"
                  onClick={scrollToPlans}
                  className="px-7 py-3.5 !bg-transparent !hover:bg-transparent border-2 border-emerald-300 text-emerald-200 font-bold rounded-md hover:!bg-emerald-300 hover:!text-[#0b1d14] transition"
                >
                  View Plans
                </button>
              </div>

              <div className="mt-8 flex flex-wrap items-center gap-5 text-sm text-slate-300">
                <span className="inline-flex items-center gap-2">
                  <Check className="w-4 h-4 text-emerald-300" /> Custom domain
                </span>
                <span className="inline-flex items-center gap-2">
                  <Check className="w-4 h-4 text-emerald-300" /> 99.9% uptime
                </span>
                <span className="inline-flex items-center gap-2">
                  <Check className="w-4 h-4 text-emerald-300" /> 24/7 support
                </span>
              </div>
            </AnimateIn>

            {/* Hero visual — stylised email / collab card mockup */}
            <AnimateIn direction="left" delay={150}>
              <div className="relative mx-auto w-full max-w-md">
                <div className="absolute -top-4 -left-4 z-10 bg-white text-slate-900 rounded-2xl shadow-xl px-4 py-2.5 flex items-center gap-2">
                  <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                  <span className="text-xs font-bold">
                    Spam blocked today · 12,940
                  </span>
                </div>

                <div className="rounded-3xl bg-white text-slate-900 shadow-2xl border border-emerald-100 overflow-hidden">
                  {/* Toolbar */}
                  <div className="bg-[#0e6305] text-white px-5 py-3 flex items-center gap-3">
                    <Mail className="w-5 h-5" />
                    <div className="text-sm font-bold flex-1">
                      Bizmail360 · Inbox
                    </div>
                    <span className="text-[11px] bg-white/15 px-2 py-0.5 rounded-full">
                      3 new
                    </span>
                  </div>

                  {/* Messages */}
                  <ul className="divide-y divide-slate-100 text-sm">
                    {[
                      {
                        from: "Finance Team",
                        subject: "Q4 budget review — draft attached",
                        time: "09:12",
                        unread: true,
                      },
                      {
                        from: "Sara Ahmed",
                        subject: "Re: Monday client onboarding",
                        time: "08:47",
                        unread: true,
                      },
                      {
                        from: "Calendar",
                        subject: "Invite: Ops sync · Tue 10:00",
                        time: "08:10",
                        unread: true,
                      },
                      {
                        from: "DoItEasy Alerts",
                        subject: "Weekly security digest",
                        time: "Yesterday",
                        unread: false,
                      },
                    ].map((m) => (
                      <li
                        key={m.subject}
                        className="px-5 py-3 flex items-start gap-3 hover:bg-slate-50 transition"
                      >
                        <div
                          className={`w-2 h-2 mt-2 rounded-full shrink-0 ${
                            m.unread ? "bg-emerald-500" : "bg-slate-300"
                          }`}
                        />
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between gap-2">
                            <span
                              className={`truncate ${
                                m.unread
                                  ? "font-bold text-[#1e3828]"
                                  : "text-slate-600"
                              }`}
                            >
                              {m.from}
                            </span>
                            <span className="text-[11px] text-slate-400 shrink-0">
                              {m.time}
                            </span>
                          </div>
                          <p
                            className={`truncate ${
                              m.unread ? "text-slate-800" : "text-slate-500"
                            }`}
                          >
                            {m.subject}
                          </p>
                        </div>
                      </li>
                    ))}
                  </ul>

                  {/* Footer */}
                  <div className="bg-slate-50 px-5 py-3 flex items-center justify-between text-xs text-slate-600">
                    <span className="inline-flex items-center gap-1.5">
                      <ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
                      TLS · DKIM · SPF · DMARC
                    </span>
                    <span className="font-semibold text-emerald-700">
                      99.9% uptime
                    </span>
                  </div>
                </div>

                <div className="absolute -bottom-4 -right-4 bg-white text-slate-900 rounded-2xl shadow-xl px-4 py-2.5">
                  <div className="text-[11px] text-slate-500">
                    Mailboxes under protection
                  </div>
                  <div className="text-lg font-extrabold text-[#0e6305]">
                    42,118
                  </div>
                </div>
              </div>
            </AnimateIn>
          </div>
        </div>
      </section>

      {/* KEY FEATURES -------------------------------------------------- */}
      <section className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="text-center mb-14 max-w-3xl mx-auto">
            <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
              Key Features
            </span>
            <h2 className="text-3xl md:text-5xl font-bold text-[#1e3828] mt-2 mb-4">
              Everything your team needs from business email
            </h2>
            <p className="text-slate-600 leading-relaxed">
              Bizmail360 combines business-grade email hosting, layered security
              and collaboration tools in one fully managed platform.
            </p>
          </AnimateIn>

          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
            {keyFeatures.map((f, idx) => (
              <AnimateIn
                key={f.title}
                delay={idx * 80}
                className="group relative rounded-3xl p-6 bg-gradient-to-br from-white to-slate-50 border border-slate-200 hover:border-[#0e6305] hover:shadow-2xl transition"
              >
                <div className="w-14 h-14 rounded-2xl bg-[#0e6305]/10 text-[#0e6305] flex items-center justify-center mb-4 group-hover:bg-[#0e6305] group-hover:text-white transition">
                  <f.icon className="w-6 h-6" />
                </div>
                <h3 className="text-lg font-bold text-[#1e3828] mb-2">
                  {f.title}
                </h3>
                <p className="text-sm text-slate-600 leading-relaxed">
                  {f.desc}
                </p>
              </AnimateIn>
            ))}
          </div>
        </div>
      </section>

      {/* COLLABORATION TOOLS ------------------------------------------- */}
      <section className="py-20 bg-slate-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid lg:grid-cols-2 gap-12 items-center">
            <AnimateIn direction="right">
              <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
                Collaboration Tools
              </span>
              <h2 className="text-3xl md:text-5xl font-bold text-[#1e3828] mt-2 mb-5 leading-tight">
                Mail, chat, meetings &amp; docs — in one workspace
              </h2>
              <p className="text-slate-600 mb-6 leading-relaxed">
                Bizmail360 unifies the four tools every team depends on — business
                mail, team chat, video meetings and collaborative docs — so your
                people stop switching apps and start moving faster.
              </p>
              <ul className="space-y-3">
                {[
                  "Start a chat or video call straight from an email thread",
                  "Co-edit docs, sheets and slides in real time",
                  "Overlay team calendars and book meeting rooms",
                  "Shared mailboxes for support@, sales@ and info@",
                ].map((t) => (
                  <li key={t} className="flex items-start gap-3">
                    <span className="w-5 h-5 rounded-full bg-[#0e6305] flex items-center justify-center shrink-0 mt-0.5">
                      <Check className="w-3 h-3 text-white" strokeWidth={3} />
                    </span>
                    <span className="text-slate-700">{t}</span>
                  </li>
                ))}
              </ul>
            </AnimateIn>

            <AnimateIn direction="left" delay={150}>
              <div className="grid sm:grid-cols-2 gap-4">
                {collabTools.map((c, idx) => (
                  <div
                    key={c.title}
                    className="group bg-white border border-slate-200 rounded-2xl p-5 hover:border-[#0e6305] hover:shadow-lg transition"
                    style={{ transitionDelay: `${idx * 40}ms` }}
                  >
                    <div className="w-11 h-11 rounded-xl bg-[#1e3828] text-white flex items-center justify-center mb-3 group-hover:bg-[#0e6305] transition">
                      <c.icon className="w-5 h-5" />
                    </div>
                    <div className="text-sm font-bold text-[#1e3828]">
                      {c.title}
                    </div>
                    <p className="text-xs text-slate-600 mt-1 leading-relaxed">
                      {c.desc}
                    </p>
                  </div>
                ))}
              </div>
            </AnimateIn>
          </div>
        </div>
      </section>

      {/* SECURITY & COMPLIANCE ---------------------------------------- */}
      <section className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="text-center mb-14 max-w-3xl mx-auto">
            <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
              Security &amp; Compliance
            </span>
            <h2 className="text-3xl md:text-5xl font-bold text-[#1e3828] mt-2 mb-4">
              Enterprise-grade security, built in
            </h2>
            <p className="text-slate-600 leading-relaxed">
              Protect your brand, your people and your data with layered
              defences — configured the right way from day one.
            </p>
          </AnimateIn>

          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {securityItems.map((s, idx) => (
              <AnimateIn
                key={s.label}
                delay={idx * 70}
                className="flex items-center gap-4 p-5 rounded-2xl bg-gradient-to-br from-[#0e6305]/5 to-white border border-emerald-100 hover:border-[#0e6305] hover:shadow-lg transition"
              >
                <div className="w-12 h-12 rounded-xl bg-[#0e6305] text-white flex items-center justify-center shrink-0">
                  <s.icon className="w-5 h-5" />
                </div>
                <div className="font-semibold text-[#1e3828]">{s.label}</div>
              </AnimateIn>
            ))}
          </div>
        </div>
      </section>

      {/* PRICING PLANS ------------------------------------------------- */}
      <section id="plans" className="py-20 bg-slate-50 scroll-mt-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="text-center mb-14 max-w-2xl mx-auto">
            <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
              Pricing Plans
            </span>
            <h2 className="text-3xl md:text-5xl font-bold text-[#1e3828] mt-2 mb-3">
              Choose the plan that fits your team
            </h2>
            <p className="text-slate-600 flex items-center justify-center gap-2">
              <Sparkles className="w-4 h-4 text-[#0e6305]" />
              Transparent per-mailbox pricing · upgrade anytime
            </p>
          </AnimateIn>

          {loadingPlans && (
            <div className="flex justify-center mb-6 text-slate-500 text-sm inline-flex items-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin" /> Loading plans…
            </div>
          )}

          <div className="grid md:grid-cols-3 gap-6">
            {plans.map((p, idx) => {
              const features = parseFeatures(p.features);
              const highlighted = Boolean(p.is_featured) || idx === 1;
              const currency = p.currency || "USD";
              const cycle = p.billing_cycle || "/mailbox/month";
              return (
                <AnimateIn
                  key={`${p.name}-${idx}`}
                  delay={idx * 120}
                  className={`relative rounded-3xl p-8 border flex flex-col transition hover:-translate-y-1 hover:shadow-2xl ${
                    highlighted
                      ? "bg-gradient-to-br from-[#0e6305] to-[#1e3828] text-white border-[#0e6305] shadow-2xl scale-[1.03]"
                      : "bg-white text-[#1e3828] border-slate-200 shadow"
                  }`}
                >
                  {highlighted && (
                    <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-[#f5c400] text-[#1e3828] text-xs font-bold px-4 py-1 rounded-full">
                      MOST POPULAR
                    </div>
                  )}
                  <div className="mb-4">
                    <h3 className="text-xl font-extrabold mb-1">{p.name}</h3>
                    {p.tagline && (
                      <p
                        className={`text-sm ${
                          highlighted ? "text-emerald-100" : "text-slate-500"
                        }`}
                      >
                        {p.tagline}
                      </p>
                    )}
                    <div className="mt-3">
                      <span
                        className={`text-4xl font-extrabold ${
                          highlighted ? "text-[#f5c400]" : "text-[#0e6305]"
                        }`}
                      >
                        {currency === "USD" ? "$" : `${currency} `}
                        {p.price}
                      </span>
                      <span
                        className={`ml-1 text-sm ${
                          highlighted ? "text-slate-200" : "text-slate-500"
                        }`}
                      >
                        {cycle}
                      </span>
                    </div>
                  </div>

                  <ul
                    className={`space-y-2.5 mb-7 text-sm flex-1 ${
                      highlighted ? "text-slate-100" : "text-slate-700"
                    }`}
                  >
                    {features.map((f) => (
                      <li key={f} className="flex items-start gap-2">
                        <Check
                          className={`w-4 h-4 shrink-0 mt-0.5 ${
                            highlighted ? "text-[#f5c400]" : "text-[#0e6305]"
                          }`}
                          strokeWidth={3}
                        />
                        <span>{f}</span>
                      </li>
                    ))}
                  </ul>

                  <div className="flex flex-col gap-2">
                    <button
                      type="button"
                      onClick={() => setPriceOpen(true)}
                      className={`block text-center py-3 rounded-md font-bold transition ${
                        highlighted
                          ? "bg-[#f5c400] text-[#1e3828] hover:bg-yellow-400"
                          : "bg-[#0e6305] text-white hover:bg-[#0a5004]"
                      }`}
                    >
                      {p.cta_label || "Get Prices"}
                    </button>
                    <button
                      type="button"
                      onClick={() => setContactOpen(true)}
                      className={`block text-center py-2.5 rounded-md font-semibold border-2 transition ${
                        highlighted
                          ? "border-white/40 text-white hover:bg-white/10"
                          : "border-[#0e6305]/30 text-[#0e6305] hover:bg-[#0e6305]/5"
                      }`}
                    >
                      Contact Sales
                    </button>
                  </div>
                </AnimateIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* WHY DOITEASY -------------------------------------------------- */}
      <section className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="text-center mb-14 max-w-2xl mx-auto">
            <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
              Why DoItEasy
            </span>
            <h2 className="text-3xl md:text-5xl font-bold text-[#1e3828] mt-2">
              The Bizmail360 advantage
            </h2>
          </AnimateIn>

          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-5">
            {whyPoints.map((w, idx) => (
              <AnimateIn
                key={w.title}
                delay={idx * 100}
                className="rounded-2xl bg-gradient-to-br from-white to-emerald-50/40 border border-slate-200 p-6 hover:border-[#0e6305] hover:shadow-xl transition"
              >
                <div className="w-12 h-12 rounded-xl bg-[#0e6305] text-white flex items-center justify-center mb-4">
                  <w.icon className="w-5 h-5" />
                </div>
                <h3 className="text-base font-bold text-[#1e3828] mb-1.5">
                  {w.title}
                </h3>
                <p className="text-sm text-slate-600 leading-relaxed">
                  {w.desc}
                </p>
              </AnimateIn>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ ----------------------------------------------------------- */}
      <section className="py-20 bg-slate-50">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="text-center mb-12">
            <span className="text-[#0e6305] font-bold uppercase tracking-widest text-sm">
              FAQ
            </span>
            <h2 className="text-3xl md:text-5xl font-bold text-[#1e3828] mt-2">
              Frequently Asked Questions
            </h2>
          </AnimateIn>

          <div className="space-y-3">
            {faqs.map((f, i) => {
              const open = openFaq === i;
              return (
                <AnimateIn
                  key={f.q}
                  delay={i * 60}
                  className="bg-white rounded-2xl border border-slate-200 hover:border-[#0e6305] transition overflow-hidden"
                >
                  <button
                    type="button"
                    onClick={() => setOpenFaq(open ? null : i)}
                    className="w-full text-left px-5 py-4 flex items-center justify-between gap-3"
                    aria-expanded={open}
                  >
                    <span className="font-bold text-[#1e3828]">{f.q}</span>
                    <ChevronDown
                      className={`w-5 h-5 text-[#0e6305] shrink-0 transition ${
                        open ? "rotate-180" : ""
                      }`}
                    />
                  </button>
                  {open && (
                    <div className="px-5 pb-5 text-slate-600 leading-relaxed text-sm">
                      {f.a}
                    </div>
                  )}
                </AnimateIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA BAND ------------------------------------------------------ */}
      <section className="py-20 bg-white">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn className="rounded-3xl bg-gradient-to-br from-[#0e6305] via-[#0a5004] to-[#1e3828] text-white p-10 md:p-14 shadow-2xl text-center relative overflow-hidden">
            <div className="absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl" />
            <div className="absolute -bottom-20 -left-20 w-72 h-72 rounded-full bg-[#f5c400]/20 blur-3xl" />
            <div className="relative">
              <Mail className="w-12 h-12 mx-auto mb-5 text-white/90" />
              <h2 className="text-3xl md:text-5xl font-extrabold mb-4">
                Ready to move your team to Bizmail360?
              </h2>
              <p className="text-slate-100 max-w-2xl mx-auto mb-8">
                Talk to our email engineers and we&apos;ll plan a zero-downtime
                migration from Google Workspace, Microsoft 365 or cPanel — on
                your schedule, with your domain, fully secured.
              </p>
              <div className="flex flex-wrap justify-center gap-3">
                <button
                  type="button"
                  onClick={() => setContactOpen(true)}
                  className="px-8 py-3.5 bg-[#f5c400] text-[#1e3828] font-bold rounded-md hover:bg-yellow-400 transition inline-flex items-center gap-2"
                >
                  <Headphones className="w-4 h-4" /> Request a Demo
                </button>
                <button
                  type="button"
                  onClick={() => setPriceOpen(true)}
                  className="px-8 py-3.5 bg-white/10 border border-white/30 text-white font-bold rounded-md hover:bg-white/20 transition inline-flex items-center gap-2"
                >
                  Get Pricing <ArrowRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          </AnimateIn>
        </div>
      </section>

      <ContactUsModal open={contactOpen} onClose={() => setContactOpen(false)} />
      <GetPriceModal open={priceOpen} onClose={() => setPriceOpen(false)} />

      <PresalesChatWidget
        sourcePage="bizmail360"
        title="Chat with Bizmail360 sales"
        subtitle="Pricing, migrations, demos — we reply fast."
        defaultTopic="pricing"
      />
    </SiteLayout>
  );
}