// Bottom sections — Workflow, Testimonials, Pricing, FAQ, CTA, Footer

// ───────── WORKFLOW ─────────
function Workflow() {
  const steps = [
    { n: "01", t: "Le client réserve", d: "Sur votre site ou directement par téléphone — la réservation arrive dans Yo car.", icon: "calendar-plus" },
    { n: "02", t: "Confirmation auto", d: "Email + SMS envoyés. Acompte demandé. Contrat pré-rempli prêt à signer.", icon: "send" },
    { n: "03", t: "Départ & check-in", d: "Photos, kilométrage, signature mobile. Tout est consigné dans le dossier.", icon: "key-round" },
    { n: "04", t: "Retour & facture", d: "Check-out, restitution caution, facture envoyée, archivage automatique.", icon: "file-check" },
  ];
  return (
    <section id="workflow" className="relative py-24 sm:py-28 bg-brand-navy text-white overflow-hidden">
      <div className="absolute inset-0 -z-10">
        <div className="absolute top-0 left-1/4 w-[500px] h-[500px] glow-orange opacity-30" />
        <div className="absolute bottom-0 right-1/4 w-[500px] h-[500px] glow-blue opacity-30" />
        <div className="absolute inset-0 grain opacity-40" />
      </div>
      <div className="max-w-7xl mx-auto px-4">
        <div className="max-w-3xl mx-auto text-center">
          <Eyebrow color="orange">Workflow</Eyebrow>
          <h2 className="font-display text-3xl sm:text-4xl md:text-5xl font-bold mt-5 leading-[1.08]" style={{ textWrap: "balance" }}>
            De la demande au paiement, en 4 étapes.
          </h2>
          <p className="mt-5 text-lg text-white/70 leading-relaxed">Un flux pensé pour les agences. Aucune étape n’est oubliée.</p>
        </div>

        <div className="mt-16 grid sm:grid-cols-2 lg:grid-cols-4 gap-4 relative">
          {/* connecting line */}
          <div className="hidden lg:block absolute top-12 left-[12%] right-[12%] h-px bg-gradient-to-r from-transparent via-white/20 to-transparent" />
          {steps.map((s, i) => (
            <Reveal key={s.n} delay={i * 100}>
              <div className="relative rounded-2xl bg-white/[0.04] ring-1 ring-white/10 p-6 backdrop-blur hover:bg-white/[0.07] transition">
                <div className="flex items-center justify-between">
                  <span className="inline-flex items-center justify-center w-12 h-12 rounded-2xl bg-brand-orange text-white shadow-lg shadow-orange-500/30">
                    <Icon name={s.icon} className="w-5 h-5" />
                  </span>
                  <span className="font-display text-3xl font-bold text-white/15">{s.n}</span>
                </div>
                <h3 className="font-display font-bold mt-5 text-lg">{s.t}</h3>
                <p className="mt-2 text-[14.5px] text-white/65 leading-relaxed">{s.d}</p>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// ───────── TESTIMONIALS ─────────
function Testimonials() {
  const list = [
    {
      quote: "On a divisé par 3 le temps passé sur les contrats. Mes équipes ne reviennent plus en arrière.",
      name: "Younes B.",
      role: "Gérant · Atlas Cars (Casablanca)",
      stars: 5,
    },
    {
      quote: "Le calendrier de disponibilité a éliminé tous nos doubles bookings. Indispensable au quotidien.",
      name: "Sara M.",
      role: "Responsable flotte · Medina Rental",
      stars: 5,
    },
    {
      quote: "Le site web synchronisé est un vrai plus. Nos prix sont toujours à jour, sans rien faire.",
      name: "Karim L.",
      role: "Fondateur · Maroc Drive",
      stars: 5,
    },
    {
      quote: "Yo IA me sort en 2 secondes mon chiffre du mois. Avant je passais une heure sur Excel.",
      name: "Hassan T.",
      role: "Directeur · Sahara Auto (Marrakech)",
      stars: 5,
    },
  ];
  return (
    <section id="testimonials" className="relative py-24 sm:py-28 bg-white">
      <div className="max-w-7xl mx-auto px-4">
        <SectionTitle
          eyebrow="Ils utilisent Yo car"
          eyebrowColor="navy"
          title="Des agences marocaines, mieux organisées."
          subtitle="Quelques retours de loueurs qui pilotent leur activité depuis Yo car."
        />
        <div className="mt-14 grid md:grid-cols-2 gap-4">
          {list.map((t, i) => (
            <Reveal key={t.name} delay={i * 80}>
              <Card className="p-7 h-full hover:shadow-card transition">
                <div className="flex gap-1 text-amber-400">
                  {Array.from({ length: t.stars }).map((_, i) => (
                    <Icon key={i} name="star" className="w-4 h-4 fill-current" />
                  ))}
                </div>
                <blockquote className="mt-4 text-brand-navy text-lg leading-relaxed font-medium" style={{ textWrap: "pretty" }}>
                  « {t.quote} »
                </blockquote>
                <div className="mt-6 flex items-center gap-3">
                  <span className="inline-flex items-center justify-center w-11 h-11 rounded-full bg-brand-navy text-white font-display font-bold">
                    {t.name.split(" ").map((s) => s[0]).slice(0, 2).join("")}
                  </span>
                  <div>
                    <div className="font-display font-bold text-brand-navy">{t.name}</div>
                    <div className="text-[12px] text-ink-400 uppercase tracking-wider">{t.role}</div>
                  </div>
                </div>
              </Card>
            </Reveal>
          ))}
        </div>

        {/* Stats row */}
        <div className="mt-14 grid grid-cols-2 sm:grid-cols-4 gap-3">
          {[
            ["+20", "agences accompagnées"],
            ["+100", "réservations traitées / mois"],
            ["4.9/5", "satisfaction clients"],
            ["−68%", "tâches manuelles"],
          ].map(([k, v]) => (
            <div key={k} className="rounded-2xl bg-ink-50 ring-1 ring-ink-100 p-6 text-center">
              <div className="font-display text-3xl sm:text-4xl font-extrabold text-brand-navy">{k}</div>
              <div className="mt-1 text-[12px] uppercase tracking-wider text-ink-400 font-semibold">{v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ───────── PRICING ─────────
function Pricing() {
  const [yearly, setYearly] = useState(true);
  const tiers = [
    {
      name: "Starter",
      tagline: "Idéal pour démarrer.",
      monthly: 290,
      yearly: 232,
      features: [
        "Jusqu’à 10 véhicules",
        "Réservations & calendrier",
        "Contrats & paiements",
        "Application mobile",
        "Support email",
      ],
      cta: "Commencer",
      variant: "ghost",
    },
    {
      name: "Pro",
      tagline: "Le choix des agences en croissance.",
      monthly: 590,
      yearly: 472,
      features: [
        "Jusqu’à 40 véhicules",
        "Site web inclus & synchronisé",
        "Automatisations avancées",
        "Assistant IA Yo IA",
        "Équipe : 5 utilisateurs",
        "Support prioritaire",
      ],
      cta: "Choisir Pro",
      variant: "primary",
      highlight: true,
    },
    {
      name: "Business",
      tagline: "Multi-agences & flotte étendue.",
      monthly: 990,
      yearly: 792,
      features: [
        "Véhicules illimités",
        "Multi-agences / multi-villes",
        "Rapports avancés & API",
        "Utilisateurs illimités",
        "SLA dédié + onboarding",
      ],
      cta: "Parler à l’équipe",
      variant: "dark",
    },
  ];
  return (
    <section id="pricing" className="relative py-24 sm:py-28 bg-ink-50">
      <div className="max-w-7xl mx-auto px-4">
        <SectionTitle
          eyebrow="Tarifs"
          title="Un prix simple, sans surprise."
          subtitle="Choisissez la formule adaptée à la taille de votre agence. Changez d’offre à tout moment."
        />
        <div className="mt-8 flex items-center justify-center gap-3">
          <span className={`text-sm font-semibold ${!yearly ? "text-brand-navy" : "text-ink-400"}`}>Mensuel</span>
          <button
            role="switch"
            aria-checked={yearly}
            onClick={() => setYearly(!yearly)}
            className={`relative w-14 h-8 rounded-full transition ${yearly ? "bg-brand-orange" : "bg-ink-200"}`}
          >
            <span className={`absolute top-1 left-1 w-6 h-6 rounded-full bg-white shadow transition-transform ${yearly ? "translate-x-6" : ""}`} />
          </button>
          <span className={`text-sm font-semibold ${yearly ? "text-brand-navy" : "text-ink-400"}`}>
            Annuel <span className="ml-1 text-[11px] px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 ring-1 ring-emerald-100 font-semibold">−20%</span>
          </span>
        </div>

        <div className="mt-12 grid lg:grid-cols-3 gap-5">
          {tiers.map((tier, i) => {
            const price = yearly ? tier.yearly : tier.monthly;
            return (
              <Reveal key={tier.name} delay={i * 80}>
                <div className={`relative h-full rounded-3xl p-7 ${tier.highlight
                  ? "bg-brand-navy text-white shadow-float ring-1 ring-brand-navy"
                  : "bg-white text-brand-navy ring-1 ring-ink-100 shadow-soft"}`}>
                  {tier.highlight && (
                    <span className="absolute -top-3 right-6 px-3 py-1 rounded-full bg-brand-orange text-white text-[11px] font-bold uppercase tracking-widest shadow-lg shadow-orange-500/40">
                      Recommandé
                    </span>
                  )}
                  <div className="flex items-center justify-between">
                    <h3 className={`font-display text-xl font-bold ${tier.highlight ? "text-white" : "text-brand-navy"}`}>{tier.name}</h3>
                    <Icon name={tier.name === "Starter" ? "rocket" : tier.name === "Pro" ? "zap" : "building-2"} className={`w-5 h-5 ${tier.highlight ? "text-brand-orange" : "text-ink-300"}`} />
                  </div>
                  <p className={`mt-1.5 text-[14px] ${tier.highlight ? "text-white/70" : "text-ink-500"}`}>{tier.tagline}</p>
                  <div className="mt-6 flex items-baseline gap-1.5">
                    <span className="font-display text-5xl font-extrabold tracking-tight">{price}</span>
                    <span className={`text-[13px] font-semibold ${tier.highlight ? "text-white/60" : "text-ink-400"}`}>MAD / mois</span>
                  </div>
                  <div className={`text-[12px] mt-1 ${tier.highlight ? "text-white/50" : "text-ink-400"}`}>
                    {yearly ? `Facturé annuellement · ${price * 12} MAD / an` : "Facturé mensuellement · sans engagement"}
                  </div>
                  <ul className="mt-6 space-y-3">
                    {tier.features.map((f) => (
                      <li key={f} className="flex items-start gap-3 text-[14.5px]">
                        <span className={`mt-0.5 inline-flex items-center justify-center w-5 h-5 rounded-full ${tier.highlight ? "bg-brand-orange/20 text-brand-orange" : "bg-emerald-50 text-emerald-600 ring-1 ring-emerald-100"}`}>
                          <Icon name="check" className="w-3 h-3" strokeWidth={3.5} />
                        </span>
                        <span className={tier.highlight ? "text-white/90" : "text-ink-700"}>{f}</span>
                      </li>
                    ))}
                  </ul>
                  <div className="mt-7">
                    <CTAButton
                      href="#cta-final"
                      variant={tier.variant}
                      size="md"
                      className={`w-full ${tier.highlight && tier.variant === "primary" ? "" : ""}`}
                      icon="arrow-right"
                    >
                      {tier.cta}
                    </CTAButton>
                  </div>
                </div>
              </Reveal>
            );
          })}
        </div>

        <div className="mt-10 text-center text-[13px] text-ink-400">
          TVA non incluse · Paiement carte ou virement · Migration et formation incluses pour Pro et Business.
        </div>
      </div>
    </section>
  );
}

// ───────── FAQ ─────────
function FAQ() {
  const qa = [
    ["Combien de temps pour démarrer ?", "Comptez 1 jour ouvré : import de votre flotte, paramétrage de votre identité, formation rapide de votre équipe."],
    ["Yo car est-il adapté au marché marocain ?", "Oui — devise MAD, factures conformes, numéros CIN/passeport, signature mobile, paramétrage darija et français."],
    ["Puis-je garder mon site web actuel ?", "Bien sûr. Vous pouvez utiliser notre site synchronisé inclus, ou connecter votre site existant via une simple intégration."],
    ["Mes données sont-elles en sécurité ?", "Données chiffrées, sauvegardes quotidiennes, accès par rôles. Hébergement européen et conforme."],
    ["Puis-je tester gratuitement ?", "Oui. Sur demande de démo, nous offrons un essai gratuit de 14 jours sur un compte complet."],
    ["Que se passe-t-il si j’arrête ?", "Vous récupérez vos données à tout moment (CSV / PDF). Aucun engagement, vous restez maître de votre activité."],
  ];
  const [open, setOpen] = useState(0);
  return (
    <section id="faq" className="relative py-24 sm:py-28 bg-white">
      <div className="max-w-4xl mx-auto px-4">
        <SectionTitle eyebrow="Questions fréquentes" eyebrowColor="navy" title="On a la réponse." subtitle="Tout ce qu’il faut savoir avant de démarrer." />
        <div className="mt-12 divide-y divide-ink-100 rounded-3xl bg-white ring-1 ring-ink-100 shadow-soft overflow-hidden">
          {qa.map(([q, a], i) => {
            const isOpen = open === i;
            return (
              <button
                key={q}
                onClick={() => setOpen(isOpen ? -1 : i)}
                className="w-full text-left px-6 sm:px-7 py-5 hover:bg-ink-50/60 transition"
              >
                <div className="flex items-center justify-between gap-6">
                  <h3 className={`font-display font-bold text-[16.5px] sm:text-lg ${isOpen ? "text-brand-orange2" : "text-brand-navy"}`}>{q}</h3>
                  <span className={`shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-full ring-1 transition ${isOpen ? "bg-brand-orange text-white ring-brand-orange" : "bg-white text-brand-navy ring-ink-200"}`}>
                    <Icon name={isOpen ? "minus" : "plus"} className="w-4 h-4" />
                  </span>
                </div>
                <div className={`grid transition-all duration-300 ${isOpen ? "grid-rows-[1fr] opacity-100 mt-3" : "grid-rows-[0fr] opacity-0"}`}>
                  <div className="overflow-hidden">
                    <p className="text-[15px] text-ink-500 leading-relaxed pr-12">{a}</p>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ───────── FINAL CTA ─────────
function FinalCTA() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  const handleSubmit = async (event) => {
    event.preventDefault();
    const form = event.currentTarget;
    setSubmitted(false);
    setSubmitError("");
    setSubmitting(true);

    try {
      const sendRequest = fetch("api/send-demo.php", {
        method: "POST",
        headers: { "Accept": "application/json" },
        body: new FormData(form),
      });
      const [response] = await Promise.all([
        sendRequest,
        new Promise((resolve) => window.setTimeout(resolve, 700)),
      ]);
      const data = await response.json().catch(() => ({}));
      if (!response.ok || !data.ok) {
        throw new Error(data.message || "Impossible d’envoyer la demande pour le moment.");
      }
      form.reset();
      setSubmitted(true);
    } catch (error) {
      setSubmitError(error.message || "Une erreur est survenue. Veuillez réessayer.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="cta-final" className="relative py-24 sm:py-28 overflow-hidden">
      <div className="max-w-7xl mx-auto px-4">
        <div className="relative rounded-[32px] overflow-hidden bg-brand-navy text-white p-10 sm:p-16">
          <div className="absolute inset-0 dots opacity-10" />
          <div className="absolute -top-32 -right-24 w-[520px] h-[520px] glow-orange opacity-70" />
          <div className="absolute -bottom-32 -left-24 w-[520px] h-[520px] glow-blue opacity-50" />
          <div className="relative grid lg:grid-cols-[1.2fr_1fr] gap-12 items-center">
            <div>
              <Eyebrow color="orange">Démarrer</Eyebrow>
              <h2 className="font-display text-4xl sm:text-5xl md:text-6xl font-extrabold mt-5 leading-[1.05]" style={{ textWrap: "balance" }}>
                Prêt à passer à Yo car&nbsp;?
              </h2>
              <p className="mt-5 text-lg text-white/70 leading-relaxed max-w-xl">
                Réservez une démo gratuite de 20 minutes. On vous montre comment Yo car peut s’adapter à votre agence — et on configure votre compte avec vous.
              </p>
              <div className="mt-8 flex flex-col sm:flex-row gap-3">
                <CTAButton href="#" size="lg" icon="calendar">Réserver une démo</CTAButton>
                <CTAButton href="#" variant="ghost" size="lg" className="!bg-white/10 !text-white !ring-white/20 hover:!bg-white/15" icon="phone">Nous appeler</CTAButton>
              </div>
              <div className="mt-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-[13px] text-white/60">
                <span className="inline-flex items-center gap-1.5"><Icon name="check" className="w-4 h-4 text-emerald-400" /> Essai 14 jours gratuits</span>
                <span className="inline-flex items-center gap-1.5"><Icon name="check" className="w-4 h-4 text-emerald-400" /> Sans carte bancaire</span>
                <span className="inline-flex items-center gap-1.5"><Icon name="check" className="w-4 h-4 text-emerald-400" /> Migration incluse</span>
              </div>
            </div>

            {/* Mini form card */}
            <div className="relative">
              <form onSubmit={handleSubmit} className="bg-white rounded-2xl p-6 sm:p-7 shadow-float text-brand-navy">
                <div className="font-display text-xl font-bold">Demander une démo</div>
                <div className="text-[13px] text-ink-400 mt-1">On vous rappelle sous 24h ouvrées.</div>
                <div className="mt-5 space-y-3">
                  {[
                    ["full_name", "Nom complet", "Karim Alaoui", "user", "text"],
                    ["agency_name", "Nom de votre agence", "Atlas Cars", "building-2", "text"],
                    ["phone", "Téléphone", "+212 6 12 34 56 78", "phone", "tel"],
                    ["email", "Email professionnel", "karim@atlas-cars.ma", "mail", "email"],
                  ].map(([name, label, ph, ic, type]) => (
                    <label key={label} className="block">
                      <span className="text-[11px] uppercase tracking-wider font-semibold text-ink-400">{label}</span>
                      <span className="mt-1 flex items-center gap-2 rounded-xl bg-ink-50 ring-1 ring-ink-100 px-3 py-2.5 focus-within:ring-brand-orange/50">
                        <Icon name={ic} className="w-4 h-4 text-ink-400" />
                        <input name={name} type={type} placeholder={ph} className="flex-1 bg-transparent text-[14px] outline-none placeholder:text-ink-300" required />
                      </span>
                    </label>
                  ))}
                </div>
                <button type="submit" disabled={submitting} className="mt-5 w-full bg-brand-orange hover:bg-brand-orange2 disabled:bg-brand-orange/70 disabled:cursor-wait text-white font-semibold py-3 rounded-xl transition shadow-[0_10px_24px_-10px_rgba(249,115,22,0.7)] inline-flex items-center justify-center gap-2">
                  {submitting ? "Envoi en cours..." : submitted ? "Demande envoyée" : "Envoyer la demande"}
                  <Icon name={submitting ? "loader-circle" : submitted ? "check" : "arrow-right"} className={`w-4 h-4 ${submitting ? "animate-spin" : ""}`} />
                </button>
                {submitted && (
                  <div className="mt-4 rounded-xl bg-emerald-50 text-emerald-700 ring-1 ring-emerald-100 px-4 py-3 text-sm font-medium flex items-start gap-2" role="status" aria-live="polite">
                    <Icon name="circle-check" className="w-4 h-4 mt-0.5" />
                    <span>Merci, votre demande a bien été envoyée. Notre équipe vous contactera bientôt.</span>
                  </div>
                )}
                {submitError && (
                  <div className="mt-4 rounded-xl bg-rose-50 text-rose-700 ring-1 ring-rose-100 px-4 py-3 text-sm font-medium flex items-start gap-2" role="alert">
                    <Icon name="circle-alert" className="w-4 h-4 mt-0.5" />
                    <span>{submitError}</span>
                  </div>
                )}
                <div className="mt-3 text-center text-[11px] text-ink-400">
                  En envoyant, vous acceptez notre politique de confidentialité.
                </div>
              </form>
              <div className="absolute -top-5 -left-5 hidden sm:block floaty">
                <div className="bg-brand-orange text-white rounded-2xl px-4 py-2.5 shadow-lg shadow-orange-500/40 flex items-center gap-2">
                  <Icon name="zap" className="w-4 h-4" />
                  <span className="text-[13px] font-bold">Démo en 20 min</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────── FOOTER ─────────
function Footer() {
  return (
    <footer className="relative bg-brand-navy text-white pt-16 pb-10">
      <div className="max-w-7xl mx-auto px-4">
        <div className="grid lg:grid-cols-[1.4fr_1fr_1fr_1fr] gap-10">
          <div>
            <BrandLogo inverted />
            <p className="mt-5 text-[14.5px] text-white/65 max-w-sm leading-relaxed">
              La plateforme tout-en-un qui aide les agences de location à mieux gérer leur flotte, leurs réservations et leurs clients.
            </p>
            <div className="mt-6 flex items-center gap-2.5">
              {["instagram", "facebook", "linkedin", "youtube"].map((ic) => (
                <a key={ic} href="#" className="inline-flex items-center justify-center w-10 h-10 rounded-full bg-white/5 ring-1 ring-white/10 hover:bg-white/10 transition">
                  <Icon name={ic} className="w-4 h-4 text-white/80" />
                </a>
              ))}
            </div>
          </div>
          {[
            ["Produit", ["Fonctionnalités", "Site web", "Automatisation", "Assistant IA", "Application mobile", "Tarifs"]],
            ["Ressources", ["Centre d’aide", "Blog", "Études de cas", "Webinars", "Contact"]],
            ["Entreprise", ["À propos", "Carrières", "Partenaires", "Mentions légales", "Confidentialité"]],
          ].map(([title, items]) => (
            <div key={title}>
              <div className="text-[11px] uppercase tracking-widest text-white/50 font-semibold">{title}</div>
              <ul className="mt-4 space-y-2.5">
                {items.map((it) => (
                  <li key={it}>
                    <a href="#" className="text-[14.5px] text-white/80 hover:text-white transition">{it}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div className="mt-14 pt-6 border-t border-white/10 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 text-[13px] text-white/50">
          <div>© {new Date().getFullYear()} Yo car. Tous droits réservés.</div>
          <div className="flex items-center gap-2">
            <Icon name="map-pin" className="w-3.5 h-3.5" />
            <span>Fait avec ❤️ pour les agences marocaines.</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Workflow, Testimonials, Pricing, FAQ, FinalCTA, Footer });
