// pricing-page.jsx: dedicated Pricing page for Locate2u PH.
// Monthly / Annual toggle, three plan cards, a grouped feature-comparison
// matrix, and a sticky bottom CTA. Uses window.l2uTokens for all branding and
// the same plan data as the homepage Pricing section. Annual = 2 months free
// (pay 10, get 12 → ~17% off) to reward longer commitments.

function PricingPage() {
  const T = window.l2uTokens;
  const [billing, setBilling] = React.useState("monthly"); // "monthly" | "annual"
  const annual = billing === "annual";
  const peso = (n) => "₱" + n.toLocaleString("en-US");

  const PLANS = [
    {
      name: "Starter",
      tag: "FOR FLEETS OF 3–9 DRIVERS",
      monthly: 795,
      desc: "Live GPS visibility and a driver app to run daily deliveries with confidence.",
      bullets: [
        "Live GPS tracking",
        "Historical route replay",
        "Geo-fencing alerts",
        "Driver app (EN + Tagalog rolling out)",
        "Stop management (up to 500 at once)",
        "Email support",
      ],
      cta: "Get started",
    },
    {
      name: "Growth",
      tag: "MOST POPULAR · 10–30 DRIVERS",
      monthly: 1114,
      featured: true,
      desc: "Full booking and route management with proof of delivery and customer tracking.",
      bullets: [
        "Everything in Starter",
        "Route optimization",
        "Proof of delivery (photo + signature)",
        "Booking management & scheduler",
        "Branded customer tracking link",
        "SMS + Viber notifications",
        "Driver ratings & reviews",
      ],
      cta: "Get started",
    },
    {
      name: "Enterprise",
      tag: "FOR LARGE FLEETS · 30+",
      monthly: null,
      desc: "API access, custom integrations, and dedicated support backed by an SLA.",
      bullets: [
        "Everything in Growth",
        "API access & webhooks",
        "Custom integrations (ERP, WMS)",
        "White-label driver app & own DNS",
        "Dedicated account manager",
        "Uptime SLA & priority support",
        "Custom reporting",
      ],
      cta: "Talk to sales",
    },
  ];

  const featured = PLANS.find((p) => p.featured);

  return (
    <div style={{ fontFamily: T.fontSans, background: T.cream, paddingBottom: 96 }}>
      {/* ── Hero + toggle ───────────────────────────────────────────── */}
      <section style={{ padding: "72px 80px 0", textAlign: "center" }}>
        <div style={{ maxWidth: 1180, margin: "0 auto" }}>
          <window.L2U_Eyebrow>PRICING</window.L2U_Eyebrow>
          <h1 style={{
            margin: "14px 0 14px", fontSize: 52, fontWeight: 900,
            lineHeight: "60px", letterSpacing: "-1.4px", color: T.bluishGrey, textWrap: "balance",
          }}>Simple pricing for Philippine fleets</h1>
          <p style={{
            margin: "0 auto 32px", maxWidth: 660, fontSize: 18, lineHeight: "28px", color: T.mute,
          }}>
            Priced per active driver. No setup fees. Save about 17% with annual billing,
            or pay monthly, every plan backed by a 30-day money-back guarantee.
          </p>
          <PricingToggle billing={billing} setBilling={setBilling} />
        </div>
      </section>

      {/* ── Plan cards ──────────────────────────────────────────────── */}
      <section style={{ padding: "44px 80px 0" }}>
        <div style={{
          maxWidth: 1180, margin: "0 auto",
          display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 24,
          alignItems: "start",
        }}>
          {PLANS.map((p) => (
            <PlanCard key={p.name} plan={p} annual={annual} peso={peso} />
          ))}
        </div>

        {/* Founding offer strip */}
        <div style={{
          maxWidth: 1180, margin: "24px auto 0",
          background: "linear-gradient(135deg, #0C2440 0%, #01101F 100%)",
          borderRadius: 16, padding: "22px 28px", color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 16,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <window.L2U_Dot color="#0BDA8E" pulse />
            <div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>Founding customer offer</div>
              <div style={{ fontSize: 13.5, color: "rgba(255,255,255,0.7)" }}>
                Be one of our first 5 PH customers and get <strong style={{ color: "#0BDA8E" }}>50% off Year 1</strong>.
              </div>
            </div>
          </div>
          <button
            onClick={() => { window.location.href = "/request-access?plan=" + encodeURIComponent("Claim founding offer"); }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "#09C07D"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "#0BDA8E"; }}
            style={{
              background: "#0BDA8E", color: "#fff", border: "none", cursor: "pointer",
              padding: "12px 20px", borderRadius: 10, fontWeight: 700, fontSize: 14, whiteSpace: "nowrap",
              transition: "background .15s ease",
            }}>Claim founding offer</button>
        </div>
      </section>

      {/* ── Comparison matrix ───────────────────────────────────────── */}
      <section style={{ padding: "72px 80px 0" }}>
        <div style={{ maxWidth: 1180, margin: "0 auto" }}>
          <h2 style={{
            fontSize: 30, fontWeight: 900, letterSpacing: "-0.6px", color: T.bluishGrey, marginBottom: 24,
          }}>Compare plans &amp; features</h2>
          {COMPARE.map((g) => (
            <CompareGroup key={g.group} group={g} />
          ))}
          <p style={{ fontSize: 12.5, color: T.mute2, marginTop: 16 }}>
            All prices in PHP, per active driver, exclusive of VAT. Annual plans are billed
            once per year (2 months free vs monthly).
          </p>
        </div>
      </section>

      {/* ── Pricing FAQ ─────────────────────────────────────────────── */}
      <PricingFAQ />

      {/* ── Sticky bottom CTA ───────────────────────────────────────── */}
      <div style={{
        position: "sticky", bottom: 0, zIndex: 20, marginTop: 56,
        background: "rgba(251,250,247,0.92)", backdropFilter: "saturate(180%) blur(8px)",
        borderTop: "1px solid rgba(28,62,97,0.10)",
        padding: "16px 80px",
      }}>
        <div style={{
          maxWidth: 1180, margin: "0 auto",
          display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 16,
        }}>
          <div>
            <div style={{ fontWeight: 800, fontSize: 16, color: T.bluishGrey }}>
              {featured.name} · {annual
                ? `${peso(Math.round(featured.monthly * 0.83) * 12)} per driver / year`
                : `${peso(featured.monthly)} per driver / mo`}
            </div>
          </div>
          <window.L2U_Btn variant="primaryLg" glow href="/request-access">Get started</window.L2U_Btn>
        </div>
      </div>
    </div>
  );
}

// ── Monthly / Annual toggle ────────────────────────────────────────────
function PricingToggle({ billing, setBilling }) {
  const T = window.l2uTokens;
  const opts = [{ k: "monthly", label: "Monthly" }, { k: "annual", label: "Annual" }];
  return (
    <div style={{
      display: "inline-flex", gap: 4, padding: 4, borderRadius: 999,
      background: "rgba(28,62,97,0.07)", border: "1px solid rgba(28,62,97,0.08)",
    }}>
      {opts.map((o) => {
        const on = billing === o.k;
        return (
          <button key={o.k} onClick={() => setBilling(o.k)}
            onMouseEnter={(e) => { if (!on) { e.currentTarget.style.background = "rgba(255,255,255,0.55)"; e.currentTarget.style.color = T.bluishGrey; } }}
            onMouseLeave={(e) => { if (!on) { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = T.mute; } }}
            style={{
            border: "none", cursor: "pointer", borderRadius: 999,
            padding: "9px 22px", fontFamily: T.fontSans, fontSize: 14, fontWeight: 600,
            background: on ? "#fff" : "transparent",
            color: on ? T.bluishGrey : T.mute,
            boxShadow: on ? "0 2px 8px rgba(15,31,56,0.12)" : "none",
            display: "inline-flex", alignItems: "center", gap: 8, transition: "background .15s ease, color .15s ease",
          }}>
            {o.label}
            {o.k === "annual" && (
              <span style={{
                fontFamily: T.fontMono, fontSize: 10, fontWeight: 700, letterSpacing: "0.4px",
                color: T.success, background: "rgba(45,210,122,0.14)", padding: "2px 6px", borderRadius: 6,
              }}>SAVE 17%</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

// ── Single plan card ───────────────────────────────────────────────────
function PlanCard({ plan, annual, peso }) {
  const T = window.l2uTokens;
  const custom = plan.monthly == null;
  // Annual billing = 17% off the monthly rate.
  const annualPerMo = custom ? 0 : Math.round(plan.monthly * 0.83);
  const annualTotal = custom ? 0 : annualPerMo * 12;
  const big = custom ? "Let's talk" : peso(annual ? annualPerMo : plan.monthly);

  return (
    <div style={{
      position: "relative", background: "#fff", borderRadius: 16, padding: 28,
      border: plan.featured ? `2px solid ${T.primary}` : "1px solid rgba(28,62,97,0.12)",
      boxShadow: plan.featured ? "0 18px 44px rgba(43,147,255,0.18)" : "0 1px 2px rgba(15,31,56,0.04)",
      display: "flex", flexDirection: "column", gap: 16,
    }}>
      {plan.featured && (
        <span style={{
          position: "absolute", top: -12, left: 24, padding: "4px 12px",
          background: T.primary, color: "#fff", borderRadius: 999,
          fontFamily: T.fontMono, fontSize: 9.5, letterSpacing: "1.2px", fontWeight: 700,
        }}>RECOMMENDED</span>
      )}
      <div>
        <div style={{ fontFamily: T.fontMono, fontSize: 10, letterSpacing: "1.2px", color: T.primaryDeep, fontWeight: 700 }}>{plan.tag}</div>
        <div style={{ fontWeight: 900, fontSize: 26, letterSpacing: "-0.4px", color: T.bluishGrey, marginTop: 8 }}>{plan.name}</div>
      </div>

      <div style={{ minHeight: 64 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
          <span style={{ fontWeight: 900, fontSize: 40, letterSpacing: "-1.4px", lineHeight: 1, color: T.bluishGrey }}>{big}</span>
          {!custom && <span style={{ fontFamily: T.fontMono, fontSize: 12, color: T.mute2 }}>/ driver / mo</span>}
        </div>
        <div style={{ marginTop: 8, fontSize: 12.5, color: T.mute, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          {custom ? (
            "Custom volume pricing for 30+ drivers"
          ) : annual ? (
            <>
              {peso(annualTotal)} per driver / year
              <span style={{
                fontFamily: T.fontMono, fontSize: 10, fontWeight: 700,
                color: T.success, background: "rgba(45,210,122,0.14)", padding: "2px 6px", borderRadius: 6,
              }}>SAVE 17%</span>
            </>
          ) : (
            "Billed monthly · no setup fees"
          )}
        </div>
      </div>

      <window.L2U_Btn
        variant={plan.featured ? "primary" : "secondary"}
        glow={plan.featured}
        href={"/request-access?plan=" + encodeURIComponent(plan.name)}
        style={{ width: "100%", justifyContent: "center" }}
      >{plan.cta}</window.L2U_Btn>

      <div style={{ borderTop: "1px solid rgba(28,62,97,0.08)", paddingTop: 16 }}>
        <div style={{ fontSize: 13.5, color: T.mute, marginBottom: 14, lineHeight: "20px" }}>{plan.desc}</div>
        <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 11 }}>
          {plan.bullets.map((b) => (
            <li key={b} style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 14, color: T.bluishGrey }}>
              <span style={{
                flexShrink: 0, width: 18, height: 18, borderRadius: "50%", marginTop: 1,
                background: "rgba(43,147,255,0.12)", display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={T.primary} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
              </span>
              {b}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

// ── Comparison data + renderers ────────────────────────────────────────
const COMPARE = [
  {
    group: "GPS tracking",
    rows: [
      { label: "Live GPS tracking", vals: ["✓", "✓", "✓"] },
      { label: "Historical route replay", vals: ["✓", "✓", "✓"] },
      { label: "Geo-fencing alerts", vals: ["✓", "✓", "✓"] },
      { label: "Route capacity management", vals: ["✓", "✓", "✓"] },
    ],
  },
  {
    group: "Stops & booking management",
    rows: [
      { label: "Stops per route", vals: ["Up to 500", "Up to 500", "Unlimited"] },
      { label: "Driver app", vals: ["✓", "✓", "✓"] },
      { label: "Shipment management", vals: ["✓", "✓", "✓"] },
      { label: "Booking management & scheduler", vals: ["✗", "✓", "✓"] },
      { label: "Web booking form", vals: ["✗", "✓", "✓"] },
      { label: "Custom fields", vals: ["✗", "✓", "✓"] },
      { label: "Barcode scanning", vals: ["✗", "✓", "✓"] },
      { label: "Start & finish questions", vals: ["✗", "✓", "✓"] },
    ],
  },
  {
    group: "Routing & delivery",
    rows: [
      { label: "Route optimization", vals: ["✗", "✓", "✓"] },
      { label: "Proof of delivery (photo + signature)", vals: ["✗", "✓", "✓"] },
      { label: "Driver ratings & reviews", vals: ["✗", "✓", "✓"] },
    ],
  },
  {
    group: "Customer notifications",
    rows: [
      { label: "Live location sharing", vals: ["✓", "✓", "✓"] },
      { label: "Branded customer tracking link", vals: ["✗", "✓", "✓"] },
      { label: "Automatic SMS notifications", vals: ["✗", "✓", "✓"] },
      { label: "Viber notifications", vals: ["✗", "✓", "✓"] },
    ],
  },
  {
    group: "Vehicle & operations",
    rows: [
      { label: "Vehicle maintenance", vals: ["✗", "✓", "✓"] },
      { label: "Team regions", vals: ["✗", "✓", "✓"] },
      { label: "Skills management", vals: ["✗", "✓", "✓"] },
    ],
  },
  {
    group: "Customizations",
    rows: [
      { label: "Logo & branding", vals: ["✗", "✓", "✓"] },
      { label: "White-label driver app", vals: ["✗", "✗", "✓"] },
      { label: "Own DNS", vals: ["✗", "✗", "✓"] },
      { label: "Custom web booking form", vals: ["✗", "✗", "✓"] },
    ],
  },
  {
    group: "Integrations",
    rows: [
      { label: "Zapier", vals: ["✗", "✓", "✓"] },
      { label: "API access & webhooks", vals: ["✗", "✗", "✓"] },
      { label: "Custom integrations (ERP, WMS)", vals: ["✗", "✗", "✓"] },
    ],
  },
  {
    group: "Support",
    rows: [
      { label: "Email support", vals: ["✓", "✓", "✓"] },
      { label: "Automatic updates", vals: ["✓", "✓", "✓"] },
      { label: "Live chat", vals: ["✗", "✓", "✓"] },
      { label: "Onboarding", vals: ["Self-serve", "Guided", "White-glove"] },
      { label: "1-on-1 phone support", vals: ["✗", "✗", "✓"] },
      { label: "Dedicated account manager", vals: ["✗", "✗", "✓"] },
      { label: "Security review", vals: ["✗", "✗", "✓"] },
      { label: "Uptime SLA", vals: ["✗", "✗", "✓"] },
    ],
  },
];

function CompareGroup({ group }) {
  const T = window.l2uTokens;
  const cols = ["Starter", "Growth", "Enterprise"];
  const colStyle = { padding: "14px 16px", textAlign: "center", fontSize: 14 };
  return (
    <div style={{
      background: "#fff", border: "1px solid rgba(28,62,97,0.10)", borderRadius: 14,
      overflow: "hidden", marginBottom: 18,
    }}>
      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 640, tableLayout: "fixed" }}>
          <colgroup>
            <col style={{ width: "40%" }} />
            <col style={{ width: "20%" }} />
            <col style={{ width: "20%" }} />
            <col style={{ width: "20%" }} />
          </colgroup>
          <thead>
            <tr style={{ background: "rgba(28,62,97,0.03)" }}>
              <th style={{ padding: "14px 18px", textAlign: "left", fontSize: 14, fontWeight: 800, color: T.bluishGrey }}>{group.group}</th>
              {cols.map((c, i) => (
                <th key={c} style={{
                  ...colStyle, fontWeight: 800,
                  color: i === 1 ? T.primaryDeep : T.bluishGrey,
                }}>{c}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {group.rows.map((r) => (
              <tr key={r.label} style={{ borderTop: "1px solid rgba(28,62,97,0.07)" }}>
                <td style={{ padding: "13px 18px", fontSize: 14, color: T.body }}>{r.label}</td>
                {r.vals.map((v, i) => (
                  <td key={i} style={{ ...colStyle, background: i === 1 ? "rgba(43,147,255,0.04)" : "transparent" }}>
                    <Cell v={v} />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Cell({ v }) {
  const T = window.l2uTokens;
  if (v === "✓") {
    return (
      <span style={{ display: "inline-flex", color: T.primary }} aria-label="Included">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
      </span>
    );
  }
  if (v === "✗" || v === "" || v == null) {
    return <span style={{ color: "rgba(28,62,97,0.28)", fontSize: 16 }} aria-label="Not included">✗</span>;
  }
  return <span style={{ color: T.bluishGrey, fontWeight: 600 }}>{v}</span>;
}

// ── Pricing FAQ (accordion) ────────────────────────────────────────────
const PRICING_FAQS = [
  {
    q: "Do you offer a free trial?",
    a: "No, we'd rather you start with confidence than kick the tyres. Every plan is backed by a 30-day money-back guarantee, so you can roll Locate2u out across your fleet and get a full refund within the first 30 days if it isn't the right fit.",
  },
  {
    q: "How does the 30-day money-back guarantee work?",
    a: "Subscribe to any plan, set it up, and use it with your real deliveries. If you're not satisfied within 30 days of your first payment, contact us and we'll refund that payment in full, no fine print.",
  },
  {
    q: "Is pricing really per driver?",
    a: "Yes. You're billed per active driver using the Locate2u driver app. Office logins (dispatchers and admins on the web dashboard) are included at no extra cost. Add or remove drivers anytime as your fleet changes.",
  },
  {
    q: "Can I change plans later?",
    a: "Absolutely. Upgrade or downgrade anytime from your account settings. Changes take effect on your next billing cycle; if you upgrade mid-cycle, you only pay the prorated difference.",
  },
  {
    q: "How does annual billing work?",
    a: "Annual plans are billed once upfront and save you about 17% versus monthly, effectively two months free. It's the best value when you're ready to commit for the year, which is why most fleets choose it.",
  },
  {
    q: "What payment methods do you accept?",
    a: "All major credit and debit cards, processed securely. Local e-wallet and InstaPay payments are coming soon. Enterprise customers can also pay by invoice with NET 30 terms.",
  },
];

function PricingFAQ() {
  const T = window.l2uTokens;
  const [open, setOpen] = React.useState(0);
  return (
    <section style={{ padding: "72px 80px 0" }}>
      <div style={{ maxWidth: 880, margin: "0 auto" }}>
        <h2 style={{ fontSize: 30, fontWeight: 900, letterSpacing: "-0.6px", color: T.bluishGrey, marginBottom: 8 }}>
          Pricing FAQ
        </h2>
        <p style={{ fontSize: 15, color: T.mute, marginBottom: 24 }}>
          Questions about plans, billing, or the money-back guarantee? Start here.
        </p>
        <div style={{ background: "#fff", border: "1px solid rgba(28,62,97,0.10)", borderRadius: 14, overflow: "hidden" }}>
          {PRICING_FAQS.map((f, i) => {
            const isOpen = open === i;
            return (
              <div key={i} style={{ borderTop: i === 0 ? "none" : "1px solid rgba(28,62,97,0.08)" }}>
                <button
                  onClick={() => setOpen(isOpen ? -1 : i)}
                  aria-expanded={isOpen}
                  onMouseEnter={(e) => { e.currentTarget.style.background = "rgba(28,62,97,0.03)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
                  style={{
                    width: "100%", background: "transparent", border: "none", cursor: "pointer",
                    padding: "20px 22px", display: "flex", alignItems: "center", justifyContent: "space-between",
                    gap: 16, textAlign: "left", transition: "background .15s ease",
                  }}>
                  <span style={{ fontSize: 16, fontWeight: 700, color: T.bluishGrey }}>{f.q}</span>
                  <span style={{
                    flexShrink: 0, width: 24, height: 24, borderRadius: "50%",
                    background: isOpen ? T.primary : "rgba(28,62,97,0.07)",
                    color: isOpen ? "#fff" : T.bluishGrey,
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    fontSize: 18, lineHeight: 1, transition: "background .15s ease",
                  }}>{isOpen ? "−" : "+"}</span>
                </button>
                {isOpen && (
                  <div style={{ padding: "0 22px 22px", fontSize: 15, lineHeight: "24px", color: T.mute, maxWidth: 720 }}>
                    {f.a}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

window.L2U_PricingPage = PricingPage;
