// Pricing + FAQ

function Pricing({ layout = "cards" }) {
  const [billing, setBilling] = useState("monthly");
  const plans = PLANS[billing];

  return (
    <section id="precios" style={{ padding: "140px 0 100px", background: "var(--cream-2)" }}>
      <div className="container">
        <Reveal stagger>
          <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 22 }}>
            <Mono>Planes &amp; precios</Mono>
            <span style={{ flex: 1, height: 1, background: "var(--line)" }} />
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "flex-end",
              justifyContent: "space-between",
              gap: 32,
              marginBottom: 56,
              flexWrap: "wrap",
            }}
          >
            <h2
              className="display"
              style={{ fontSize: "clamp(40px, 5.6vw, 76px)", maxWidth: 760 }}
            >
              Empieza gratis.<br />
              Sube cuando <em>el plan</em><br />
              empiece a funcionar.
            </h2>

            <BillingToggle billing={billing} setBilling={setBilling} />
          </div>
        </Reveal>

        {layout === "table" ? (
          <PricingTable plans={plans} />
        ) : (
          <PricingCards plans={plans} />
        )}

        <Reveal>
          <p
            style={{
              textAlign: "center",
              marginTop: 48,
              fontSize: 14,
              color: "var(--ink-muted)",
            }}
          >
            Todos los planes incluyen: método completo · Export a PDF · IA entrenada en marketing ·
            Acceso a actualizaciones
          </p>
        </Reveal>
      </div>
    </section>
  );
}

function BillingToggle({ billing, setBilling }) {
  return (
    <div
      style={{
        display: "inline-flex",
        padding: 4,
        borderRadius: 999,
        background: "rgba(14,34,54,0.06)",
        border: "1px solid var(--line)",
        position: "relative",
      }}
    >
      {["monthly", "annual"].map((b) => (
        <button
          key={b}
          onClick={() => setBilling(b)}
          style={{
            padding: "9px 18px",
            borderRadius: 999,
            border: "none",
            background: billing === b ? "var(--ink)" : "transparent",
            color: billing === b ? "var(--cream)" : "var(--ink-soft)",
            fontSize: 13,
            fontWeight: 500,
            transition: "all 0.25s ease",
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          {b === "monthly" ? "Mensual" : "Anual"}
          {b === "annual" && (
            <span
              style={{
                fontSize: 10,
                fontFamily: "var(--font-mono)",
                padding: "2px 6px",
                borderRadius: 4,
                background: billing === b ? "var(--accent)" : "var(--accent-soft)",
                color: billing === b ? "white" : "var(--ink)",
                letterSpacing: "0.06em",
              }}
            >
              −17%
            </span>
          )}
        </button>
      ))}
    </div>
  );
}

function PricingCards({ plans }) {
  return (
    <Reveal stagger>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 20,
        }}
        className="pricing-grid"
      >
        {plans.map((plan) => (
          <PricingCard key={plan.id} plan={plan} />
        ))}
      </div>
      <style>{`
        @media (max-width: 1100px) {
          .pricing-grid { grid-template-columns: repeat(2, 1fr) !important; }
        }
        @media (max-width: 580px) {
          .pricing-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </Reveal>
  );
}

function PricingCard({ plan }) {
  const featured = plan.featured;
  return (
    <div
      style={{
        background: featured ? "var(--ink)" : "rgba(255,255,255,0.55)",
        color: featured ? "var(--cream)" : "var(--ink)",
        borderRadius: 18,
        padding: "32px 26px 28px",
        border: featured ? "1px solid var(--ink)" : "1px solid var(--line)",
        position: "relative",
        display: "flex",
        flexDirection: "column",
        gap: 18,
        boxShadow: featured ? "0 30px 60px -30px rgba(14,34,54,0.5)" : "none",
        transform: featured ? "translateY(-8px)" : "none",
      }}
    >
      {featured && (
        <span
          style={{
            position: "absolute",
            top: -12,
            left: 24,
            background: "var(--accent)",
            color: "white",
            fontFamily: "var(--font-mono)",
            fontSize: 10,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            padding: "5px 10px",
            borderRadius: 4,
          }}
        >
          Más popular
        </span>
      )}

      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
        <h3 className="display" style={{ fontSize: 32, color: "inherit" }}>
          {plan.name}
        </h3>
        {plan.badge && (
          <span
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: 10,
              letterSpacing: "0.12em",
              padding: "3px 8px",
              borderRadius: 4,
              background: featured ? "rgba(243,183,158,0.18)" : "rgba(221,90,51,0.15)",
              color: featured ? "var(--accent-soft)" : "var(--accent)",
            }}
          >
            {plan.badge}
          </span>
        )}
      </div>

      <p
        style={{
          fontSize: 14,
          color: featured ? "rgba(239,232,218,0.75)" : "var(--ink-muted)",
          minHeight: 42,
        }}
      >
        {plan.tagline}
      </p>

      <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
        <span
          className="display"
          style={{
            fontSize: plan.price === "Custom" ? 36 : 48,
            color: "inherit",
            letterSpacing: "-0.03em",
          }}
        >
          
          {plan.price}
        </span>
        <span
          style={{
            fontSize: 13,
            color: featured ? "rgba(239,232,218,0.65)" : "var(--ink-muted)",
          }}
        >
          {plan.cadence}
        </span>
      </div>

      <a
        href={
          plan.id === "free" ? "https://app.mediaplanningcanvas.com/registro" :
          plan.id === "pro" ? "https://app.mediaplanningcanvas.com/perfil?tab=plan&upgrade=pro" :
          plan.id === "business" ? "https://app.mediaplanningcanvas.com/perfil?tab=plan&upgrade=business" :
          "mailto:hola@mediaplanningcanvas.com"
        }
        className={featured ? "btn btn-accent" : "btn btn-ink"}
        style={{
          width: "100%",
          justifyContent: "center",
          ...(featured
            ? {}
            : { background: "transparent", color: "inherit", border: "1px solid var(--line-strong)" }),
        }}
      >
        {plan.cta}
      </a>

      <div
        style={{
          height: 1,
          background: featured ? "rgba(239,232,218,0.18)" : "var(--line)",
          margin: "4px 0",
        }}
      />

      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {plan.features.map((f, i) => (
          <li
            key={i}
            style={{
              display: "flex",
              gap: 10,
              alignItems: "flex-start",
              fontSize: 13.5,
              lineHeight: 1.45,
              color: f.muted
                ? featured
                  ? "rgba(239,232,218,0.5)"
                  : "var(--ink-muted)"
                : "inherit",
              fontWeight: f.strong ? 500 : 400,
            }}
          >
            <span
              style={{
                width: 14,
                height: 14,
                borderRadius: 3,
                background: f.muted
                  ? "transparent"
                  : featured
                  ? "var(--accent-soft)"
                  : "var(--ink)",
                color: featured ? "var(--ink)" : "var(--cream)",
                display: "grid",
                placeItems: "center",
                fontSize: 9,
                flexShrink: 0,
                marginTop: 3,
                border: f.muted
                  ? `1px dashed ${featured ? "rgba(239,232,218,0.35)" : "var(--line-strong)"}`
                  : "none",
              }}
            >
              {f.muted ? "–" : "✓"}
            </span>
            <span>{f.text}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Table-style pricing variant
function PricingTable({ plans }) {
  // Build a feature matrix from semantic keys
  const rows = [
    { k: "Planes activos", get: (p) => featureValue(p, "planes") },
    { k: "Análisis IA", get: (p) => featureValue(p, "análisis ia") },
    { k: "Mejoras IA", get: (p) => featureValue(p, "mejoras ia") },
    { k: "Renovación", get: (p) => (p.id === "free" ? "Sin renovación" : "Mensual") },
    { k: "Video clases & herramientas", get: (p) => (p.id === "free" ? "Limitado" : "✓") },
    { k: "Calculadora táctica avanzada", get: (p) => (p.id === "free" ? "—" : "✓") },
    { k: "Export PDF", get: () => "✓" },
    { k: "Soporte", get: (p) => (p.id === "enterprise" ? "Prioritario" : "Email") },
  ];

  return (
    <Reveal>
      <div
        style={{
          background: "rgba(255,255,255,0.55)",
          border: "1px solid var(--line)",
          borderRadius: 18,
          overflow: "hidden",
        }}
      >
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "minmax(180px, 1.4fr) repeat(4, minmax(140px, 1fr))",
            borderBottom: "1px solid var(--line)",
          }}
          className="ptable-row"
        >
          <div style={{ padding: "24px 22px" }} />
          {plans.map((p) => (
            <div
              key={p.id}
              style={{
                padding: "24px 22px",
                borderLeft: "1px solid var(--line)",
                background: p.featured ? "var(--ink)" : "transparent",
                color: p.featured ? "var(--cream)" : "var(--ink)",
              }}
            >
              <div className="display" style={{ fontSize: 28 }}>{p.name}</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4, marginTop: 6 }}>
                <span className="display" style={{ fontSize: 28 }}>
                  {p.price}
                </span>
                <span style={{ fontSize: 12, color: p.featured ? "rgba(239,232,218,0.65)" : "var(--ink-muted)" }}>
                  {p.cadence}
                </span>
              </div>
              <a
                href="#descargar"
                className={p.featured ? "btn btn-accent" : "btn btn-ghost"}
                style={{
                  marginTop: 14,
                  width: "100%",
                  justifyContent: "center",
                  fontSize: 13,
                  padding: "10px 14px",
                  ...(p.featured
                    ? {}
                    : { borderColor: p.featured ? "rgba(239,232,218,0.3)" : "var(--line-strong)" }),
                }}
              >
                {p.cta}
              </a>
            </div>
          ))}
        </div>

        {rows.map((row, i) => (
          <div
            key={row.k}
            className="ptable-row"
            style={{
              display: "grid",
              gridTemplateColumns: "minmax(180px, 1.4fr) repeat(4, minmax(140px, 1fr))",
              borderBottom: i === rows.length - 1 ? "none" : "1px solid var(--line)",
              background: i % 2 === 0 ? "transparent" : "rgba(14,34,54,0.025)",
            }}
          >
            <div style={{ padding: "16px 22px", fontSize: 14, color: "var(--ink-soft)" }}>{row.k}</div>
            {plans.map((p) => (
              <div
                key={p.id}
                style={{
                  padding: "16px 22px",
                  borderLeft: "1px solid var(--line)",
                  fontSize: 14,
                  fontFamily: "var(--font-mono)",
                  fontWeight: 500,
                }}
              >
                {row.get(p)}
              </div>
            ))}
          </div>
        ))}
      </div>
      <style>{`
        @media (max-width: 900px) {
          .ptable-row { grid-template-columns: 1fr !important; }
          .ptable-row > div { border-left: none !important; border-top: 1px solid var(--line) !important; }
        }
      `}</style>
    </Reveal>
  );
}

function featureValue(plan, contains) {
  const f = plan.features.find((x) => x.text.toLowerCase().includes(contains));
  if (!f) return "—";
  // Extract leading number-ish content
  const m = f.text.match(/^(?:Hasta\s)?([0-9.]+|999)/i);
  if (m) return m[0] + (contains === "planes" ? " planes" : "");
  return f.text.split(",")[0];
}

// FAQ accordion
function FAQSection() {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq" style={{ padding: "140px 0 120px" }}>
      <div className="container">
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.4fr)",
            gap: 80,
            alignItems: "start",
          }}
          className="faq-grid"
        >
          <Reveal>
            <Mono>FAQ</Mono>
            <h2 className="display" style={{ fontSize: "clamp(40px, 5vw, 64px)", marginTop: 18 }}>
              Preguntas que <em>casi todo</em> el mundo nos hace.
            </h2>
            
          </Reveal>

          <Reveal>
            <div style={{ borderTop: "1px solid var(--line)" }}>
              {FAQ.map((f, i) => {
                const isOpen = open === i;
                return (
                  <div
                    key={i}
                    style={{ borderBottom: "1px solid var(--line)" }}
                  >
                    <button
                      onClick={() => setOpen(isOpen ? -1 : i)}
                      style={{
                        width: "100%",
                        textAlign: "left",
                        background: "transparent",
                        border: "none",
                        padding: "22px 0",
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        gap: 24,
                        color: "var(--ink)",
                        fontSize: 18,
                        fontWeight: 500,
                        fontFamily: "var(--font-body)",
                        letterSpacing: "-0.005em",
                      }}
                    >
                      <span>{f.q}</span>
                      <span
                        style={{
                          width: 28,
                          height: 28,
                          borderRadius: 999,
                          border: "1px solid var(--line-strong)",
                          display: "grid",
                          placeItems: "center",
                          fontSize: 16,
                          color: "var(--ink-soft)",
                          flexShrink: 0,
                          transform: isOpen ? "rotate(45deg)" : "rotate(0)",
                          transition: "transform 0.3s ease",
                        }}
                      >
                        +
                      </span>
                    </button>
                    <div
                      style={{
                        maxHeight: isOpen ? 400 : 0,
                        overflow: "hidden",
                        transition: "max-height 0.4s ease, opacity 0.3s ease, padding 0.3s ease",
                        opacity: isOpen ? 1 : 0,
                        paddingBottom: isOpen ? 24 : 0,
                      }}
                    >
                      <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--ink-soft)", maxWidth: 720 }}>
                        {f.a}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>
          </Reveal>
        </div>

        <style>{`
          @media (max-width: 880px) {
            .faq-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

Object.assign(window, { Pricing, FAQSection });
