// ============================================
// Reliq — Payment setup step
// Private route: /payment?plan=starter&trial=7d
//
// Step 9: replaces the mock card-collection form with a real Stripe Checkout
// redirect. The frontend NEVER handles raw card data.
//
//   1. Reads plan from URL hash query param (or localStorage fallback)
//   2. Calls POST /v1/billing/checkout → receives { checkoutUrl }
//   3. Redirects the browser to checkoutUrl (Stripe-hosted checkout)
//   4. Stripe collects payment, then redirects back to BILLING_SUCCESS_URL
//      (configured on the backend as APP_URL/#/billing/success)
//
// Invariants:
//   - No card numbers, expiry, or CVC ever reach this page
//   - activateTrial() is NOT called from the frontend
//   - Billing truth is established by Stripe webhook (invoice.paid / customer.subscription.updated)
//   - Success message: "Payment setup received. Reliq will update your access once Stripe confirms."
//
// Step 9 — Frontend billing UI integration and state handling.
// ============================================

// ── Plan metadata (display only — prices come from backend /v1/billing/plans) ─
const PAY_PLANS = {
  starter: { name: "Starter", priceStr: "$29" },
  pro:     { name: "Pro",     priceStr: "$79" },
  team:    { name: "Team",    priceStr: "$199" },
};

// ── Read trial plan from hash query params, fall back to localStorage ─────────
// Priority order:
//   1. ?plan= query param in the current hash (most reliable)
//   2. reliq_selected_plan — written by reliqSubscription.setPendingPayment()
//   3. reliq_trial_plan    — legacy key; cleaned up by activateTrial()
//   4. "starter" as safe default
const readPaymentPlan = () => {
  try {
    const hash = window.location.hash;
    const qi = hash.indexOf("?");
    if (qi >= 0) {
      const p = new URLSearchParams(hash.slice(qi + 1));
      const plan = p.get("plan");
      if (plan && PAY_PLANS[plan]) return plan;
    }
    const selected = localStorage.getItem("reliq_selected_plan");
    if (selected && PAY_PLANS[selected]) return selected;
    const legacy = localStorage.getItem("reliq_trial_plan");
    if (legacy && PAY_PLANS[legacy]) return legacy;
  } catch (_) {}
  return "starter";
};

// ── Spinner ────────────────────────────────────────────────────────────────────
const SpinIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24"
       style={{ animation: "spin 1s linear infinite", flexShrink: 0 }}>
    <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2.5"
            fill="none" strokeDasharray="40 60" strokeLinecap="round" />
  </svg>
);

// ── PaymentStep component ──────────────────────────────────────────────────────
const PaymentStep = ({ go }) => {
  const planKey = React.useRef(readPaymentPlan()).current;
  const plan    = PAY_PLANS[planKey] || PAY_PLANS.starter;

  const [submitting, setSubmitting] = React.useState(false);
  const [error,      setError]      = React.useState(null);

  // ── Initiate Stripe Checkout session ───────────────────────────────────────
  // POST /v1/billing/checkout → { checkoutUrl }
  // Then redirect the browser to checkoutUrl (Stripe-hosted, no card data here).
  const handleStartPayment = async () => {
    if (submitting) return;
    setError(null);
    setSubmitting(true);
    try {
      const result = await window.reliqBillingApi?.startCheckout?.(planKey);
      if (result?.checkoutUrl) {
        // Full-page redirect to Stripe Checkout.
        // Stripe will redirect back to BILLING_SUCCESS_URL on success,
        // or BILLING_CANCEL_URL on cancel (both configured on the backend).
        window.location.href = result.checkoutUrl;
      } else {
        setError("Could not start checkout. Please try again.");
        setSubmitting(false);
      }
    } catch (err) {
      setError(err.message || "Could not start checkout. Please try again.");
      setSubmitting(false);
    }
  };

  // ── Trial end date (today + 7 days) — display only ─────────────────────────
  const trialEnd = new Date();
  trialEnd.setDate(trialEnd.getDate() + 7);
  const endStr = trialEnd.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });

  return (
    <LandingLayout go={go} pageTitle="Set up payment">
      <div style={{ maxWidth: 460, margin: "0 auto" }}>

        {/* ── Header ── */}
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <div style={{
            width: 52, height: 52, borderRadius: "var(--r-md)", margin: "0 auto 18px",
            background: "var(--bg-3)", border: "1px solid var(--line-2)",
            display: "grid", placeItems: "center", color: "var(--teal)",
          }}>
            <Icon name="lock" size={22} />
          </div>
          <h1 style={{
            fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 600,
            letterSpacing: "-0.02em", margin: "0 0 8px", color: "var(--fg-0)",
          }}>
            Set up your payment method
          </h1>
          <p style={{ color: "var(--fg-2)", fontSize: 13.5, lineHeight: 1.65, margin: 0 }}>
            You won't be charged until your trial ends on <strong style={{ color: "var(--fg-1)" }}>{endStr}</strong>.
            Payment is handled securely by Stripe.
          </p>
        </div>

        {/* ── Plan summary card ── */}
        <div style={{
          border: "1px solid var(--line-2)", borderRadius: "var(--r-lg)",
          padding: "14px 18px", marginBottom: 24, background: "var(--bg-1)",
          display: "flex", alignItems: "center", justifyContent: "space-between",
        }}>
          <div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
              textTransform: "uppercase", color: "var(--teal)", marginBottom: 4,
            }}>
              Selected plan
            </div>
            <div style={{
              fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, color: "var(--fg-0)",
            }}>
              {plan.name}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--fg-2)", marginTop: 3 }}>
              7-day free trial · then {plan.priceStr}/mo
            </div>
          </div>
          <div>
            <span style={{
              fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 700, color: "var(--fg-0)",
            }}>{plan.priceStr}</span>
            <span style={{ fontSize: 12, color: "var(--fg-3)" }}>/mo</span>
          </div>
        </div>

        {/* ── What happens next ── */}
        <div style={{
          border: "1px solid var(--line-1)", borderRadius: "var(--r-md)",
          padding: "14px 18px", marginBottom: 24, background: "var(--bg-2)",
          fontSize: 13, color: "var(--fg-2)", lineHeight: 1.65,
          display: "flex", flexDirection: "column", gap: 10,
        }}>
          <div style={{ fontWeight: 600, color: "var(--fg-1)", fontSize: 13.5 }}>
            <Icon name="info" size={14} style={{ verticalAlign: "middle", marginRight: 6 }} />
            How it works
          </div>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
            <span style={{ color: "var(--teal)", fontWeight: 700, minWidth: 18 }}>1.</span>
            You'll be redirected to Stripe's secure checkout page to add your card.
          </div>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
            <span style={{ color: "var(--teal)", fontWeight: 700, minWidth: 18 }}>2.</span>
            Your 7-day trial starts when Stripe confirms your payment method.
          </div>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
            <span style={{ color: "var(--teal)", fontWeight: 700, minWidth: 18 }}>3.</span>
            You won't be charged until {endStr}. Cancel anytime before then.
          </div>
        </div>

        {/* ── Error message ── */}
        {error && (
          <div style={{
            padding: "10px 14px", borderRadius: "var(--r-md)", marginBottom: 16,
            background: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.35)",
            fontSize: 13, color: "var(--red)", display: "flex", alignItems: "center", gap: 8,
          }}>
            <Icon name="alert" size={14} /> {error}
          </div>
        )}

        {/* ── Proceed button ── */}
        <button
          type="button"
          className="btn btn-primary btn-lg"
          disabled={submitting}
          onClick={handleStartPayment}
          style={{
            width: "100%", justifyContent: "center",
            opacity: submitting ? 0.75 : 1,
            cursor:  submitting ? "not-allowed" : "pointer",
          }}
          aria-label={`Set up payment for ${plan.name} trial`}
        >
          {submitting
            ? <><SpinIcon size={14} /> Redirecting to Stripe…</>
            : <>Continue to payment <Icon name="arrow-right" size={14} /></>
          }
        </button>

        {/* ── Security note ── */}
        <div style={{
          marginTop: 16, textAlign: "center",
          fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-3)",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
        }}>
          <Icon name="lock" size={11} />
          256-bit TLS encryption · Powered by Stripe · Cancel anytime before {endStr}
        </div>

        {/* ── Back link ── */}
        <div style={{ marginTop: 20, textAlign: "center" }}>
          <button
            className="btn btn-ghost btn-sm"
            onClick={() => go("/billing")}
            style={{ fontSize: 13, color: "var(--fg-3)" }}
          >
            ← Back to billing
          </button>
        </div>

      </div>
    </LandingLayout>
  );
};

Object.assign(window, { PaymentStep });
