// Pricing — sticky plan-header cards above a categorized comparison table,
// with the "Recommended" Pro column visually continuous (tinted background,
// border highlight, gradient header card).

const PRICING_V4_PLANS = [
  {
    id: "free",
    name: "Free",
    tagline: "Try the full app for 15 days.*",
    priceM: 0, priceY: 0,
    cta: "Start trial",
    primary: false,
  },
  {
    id: "starter",
    name: "Starter",
    tagline: "Core analytics.",
    priceM: 9.99, priceY: 8.49,
    cta: "Choose Starter",
    primary: false,
  },
  {
    id: "pro",
    name: "Pro",
    tagline: "Full access.",
    priceM: 19.99, priceY: 16.99,
    cta: "Choose Pro",
    primary: true,
    recommended: true,
  },
];

const PRICING_V4_GROUPS = [
  {
    title: "Core analytics",
    rows: [
      ["Portfolios",                          "Unlimited", "1",   "Unlimited"],
      ["Strategies",                          "Unlimited", "3",   "Unlimited"],
      ["Open positions",                      "Unlimited", "20",  "Unlimited"],
      ["Flex Query import",                   true,        true,  true],
      ["Manual + CSV Historical Import",      true,        true,  true],
      ["Customizable dashboard (drag & drop)", true,       true,  true],
      ["Dividends & withholding export",      true,        true,  true],
      ["Full performance analytics",          true,        true,  true],
      ["Portfolio comparison",                true,        true,  true],
      ["FIFO lifecycle & Corporate actions (splits, mergers, aliases)", true, true, true],
      ["New features & updates included",     true,        true,  true],
    ],
  },
  {
    title: "Automation",
    rows: [
      ["Multi-currency P&L (USD, CAD, AUD & more)", true,  true,  true],
      ["Desktop sync agent",                  true,  false, true],
      ["Earnings & upcoming dividends",       true,  false, true],
    ],
  },
  {
    title: "Systematic workflow",
    rows: [
      ["OrderClerk reconciliation",           true, false, true],
      ["RealTest & Upcoming Orders",          true, false, true],
      ["Roundtrip Builder",                   true, false, true],
      ["Full Capital Allocation",             true, false, true],
      ["Multi-account lifecycles",            true, false, true],
    ],
  },
];

// CTA destination: hand the chosen plan + billing cycle to the checkout page
// via query params. Free goes straight to the trial path (no cycle).
function pricingV4CheckoutHref(plan, annual) {
  if (plan.id === "free") return "/checkout?plan=free";
  return `/checkout?plan=${plan.id}&cycle=${annual ? "annual" : "monthly"}`;
}

function PricingV4Cell({ v, highlight }) {
  if (typeof v === "string") {
    return (
      <span className={`num text-[13px] tabular-nums ${highlight ? "text-fg font-medium" : "text-fg"}`}>
        {v}
      </span>
    );
  }
  if (v === true) {
    return (
      <span
        className={`inline-flex items-center justify-center h-5 w-5 rounded-full ${
          highlight
            ? "bg-primary/20 text-primary ring-1 ring-primary/40"
            : "bg-positive/10 text-positive"
        }`}
      >
        <IcoCheck size={12} />
      </span>
    );
  }
  return <span className="text-subtlefg text-base leading-none select-none">—</span>;
}

function PricingV4PlanHeader({ plan, annual }) {
  const isPro = plan.primary;

  return (
    <div
      className={`relative h-full rounded-xl p-5 md:p-6 flex flex-col transition-all ${
        isPro
          ? "bg-gradient-to-b from-primary/15 via-primary/[0.08] to-card border border-primary/40 shadow-[0_0_40px_-12px_hsl(var(--primary)/.4)]"
          : "bg-card border border-border1"
      }`}
    >
      {plan.recommended && (
        <div className="absolute -top-3 left-1/2 -translate-x-1/2 whitespace-nowrap">
          <span className="inline-flex items-center gap-1 rounded-full bg-primary text-primaryFg px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] shadow-md">
            <IcoSparkle size={10} /> Recommended
          </span>
        </div>
      )}

      <div className="flex items-baseline justify-between gap-2">
        <h3 className="text-[17px] font-semibold tracking-tight text-fg">
          {plan.name}
        </h3>
        {!isPro && plan.id === "starter" && (
          <span className="text-[10px] text-subtlefg uppercase tracking-wider">Basic</span>
        )}
        {!isPro && plan.id === "free" && (
          <span className="text-[10px] text-subtlefg uppercase tracking-wider">Trial</span>
        )}
      </div>

      <p className="mt-1 text-[12px] text-mutedfg leading-relaxed">
        {plan.tagline.endsWith("*") ? (
          <>
            {plan.tagline.slice(0, -1)}
            <span className="text-primary">*</span>
          </>
        ) : (
          plan.tagline
        )}
      </p>

      <div className="mt-3 flex flex-col">
        <div className="flex items-baseline gap-1.5 flex-wrap">
          <span className="num font-semibold tracking-tight text-fg text-[34px] md:text-[38px] leading-none">
            {plan.id === "free"
              ? "$0"
              : annual
              ? `$${plan.priceY.toFixed(2)}`
              : `$${plan.priceM.toFixed(2)}`}
          </span>
          <span className="text-[11.5px] text-mutedfg whitespace-nowrap">
            {plan.id === "free" ? "15 days" : "/ mo"}
          </span>
        </div>

        {annual && plan.priceM > 0 && (
          <div className="mt-2 flex items-center gap-2 flex-wrap">
            <span className="inline-flex items-center gap-1 rounded-md bg-positive/15 text-positive border border-positive/30 px-1.5 py-0.5 text-[10.5px] font-semibold leading-none num">
              Save ${((plan.priceM - plan.priceY) * 12).toFixed(2)}
            </span>
            <span className="num text-[11px] text-mutedfg line-through decoration-mutedfg/60">
              ${plan.priceM.toFixed(2)} / mo
            </span>
          </div>
        )}

        {annual && plan.priceM > 0 && (
          <div className="mt-1.5 text-[10.5px] text-subtlefg num whitespace-nowrap">
            Billed ${(plan.priceY * 12).toFixed(2)} once a year
          </div>
        )}

        {!annual && plan.priceM > 0 && (
          <div className="mt-2 flex items-center gap-2 flex-wrap">
            <span className="inline-flex items-center gap-1 rounded-md bg-positive/10 text-positive border border-positive/25 px-1.5 py-0.5 text-[10.5px] font-medium leading-none num">
              Save 15% annually
            </span>
            <span className="text-[10.5px] text-subtlefg">Cancel anytime</span>
          </div>
        )}

        {plan.priceM === 0 && (
          <div className="mt-2 text-[10.5px] text-subtlefg">No credit card required</div>
        )}
      </div>

      <div className="mt-auto pt-4">
        <a
          href={pricingV4CheckoutHref(plan, annual)}
          className={`flex items-center justify-center gap-1.5 rounded-md py-2.5 text-[13px] font-semibold transition-colors ${
            isPro
              ? "bg-primary text-primaryFg hover:brightness-110"
              : "bg-card2 text-fg border border-border1 hover:border-primary/40 hover:text-primary"
          }`}
        >
          {plan.cta} {isPro && <IcoArrowRight size={13} />}
        </a>
      </div>
    </div>
  );
}

function PricingV4Content() {
  const [annual, setAnnual] = React.useState(false);

  return (
    <>
      {/* "Choose your plan" header bar — left: title + subtitle, right: Monthly/Annual toggle */}
      <div className="-mt-2 md:-mt-4 flex flex-col md:flex-row md:items-center justify-between gap-4 pb-5 mb-6 border-b border-border1">
        <div>
          <h3 className="text-[18px] font-semibold tracking-tight text-fg">Choose your plan</h3>
          <p className="mt-1 text-[12px] text-subtlefg">
            Free for 15 days · upgrade anytime · cancel whenever
          </p>
        </div>
        <div className="flex items-center gap-3 self-start md:self-auto">
          <span className="text-[12.5px] text-subtlefg">
            <span className="text-primary">†</span> Prices in USD
          </span>
          <div className="inline-flex items-center gap-1 rounded-full border border-border1 bg-card2/60 backdrop-blur p-1">
            <button
              type="button"
              onClick={() => setAnnual(false)}
              className={`px-4 py-1.5 text-[12.5px] font-medium rounded-full transition-all ${
                !annual ? "bg-bg text-fg shadow-sm" : "text-mutedfg hover:text-fg"
              }`}
            >
              Monthly
            </button>
            <button
              type="button"
              onClick={() => setAnnual(true)}
              className={`inline-flex items-center gap-2 pl-4 pr-3 py-1.5 text-[12.5px] font-medium rounded-full transition-all ${
                annual ? "bg-bg text-fg shadow-sm" : "text-mutedfg hover:text-fg"
              }`}
            >
              Annual
              <span className="inline-flex items-center justify-center rounded-full bg-positive/15 text-positive px-2 py-[3px] text-[10px] font-semibold leading-none">
                Save 15%
              </span>
            </button>
          </div>
        </div>
      </div>

      {/* ---------------- DESKTOP: comparison table ---------------- */}
      <div className="hidden md:block">
        <div className="relative">
          {/* Plan headers row aligned with feature table columns below */}
          <div className="grid grid-cols-[38%_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-x-2 mb-3 items-stretch">
            <div></div>
            {PRICING_V4_PLANS.map((p) => (
              <div key={p.id} className="min-w-0 h-full">
                <PricingV4PlanHeader plan={p} annual={annual} />
              </div>
            ))}
          </div>

          {/* Feature table */}
          <div className="rounded-xl border border-border1 bg-card/40 overflow-hidden">
            {PRICING_V4_GROUPS.map((group) => (
              <div key={group.title}>
                {/* Group header — the plan name is repeated on every section
                    band so each column stays identifiable once the plan cards
                    have scrolled out of view. Pro keeps its violet tint. */}
                <div className="grid grid-cols-[38%_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-x-2 bg-card2/60 border-b border-border2">
                  <div className="px-5 py-3 text-[10.5px] font-semibold uppercase tracking-[0.16em] text-subtlefg">
                    {group.title}
                  </div>
                  {PRICING_V4_PLANS.map((p) => (
                    <div
                      key={p.id}
                      className={`px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-[0.14em] ${
                        p.primary
                          ? "bg-primary/[0.06] border-x border-primary/15 -my-px text-primary"
                          : "text-mutedfg"
                      }`}
                    >
                      {p.name}
                    </div>
                  ))}
                </div>

                {group.rows.map((row, ri) => {
                  const [label, fv, sv, pv] = row;
                  return (
                    <div
                      key={ri}
                      className={`group grid grid-cols-[38%_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-x-2 items-center border-b border-border2/60 transition-colors hover:bg-card2/30 ${
                        ri % 2 === 1 ? "bg-card2/20" : ""
                      }`}
                    >
                      <div className="px-5 py-2 text-[13.5px] text-fg">{label}</div>
                      <div className="px-3 py-2 text-center">
                        <PricingV4Cell v={fv} />
                      </div>
                      <div className="px-3 py-2 text-center">
                        <PricingV4Cell v={sv} />
                      </div>
                      <div className="px-3 py-2 text-center bg-primary/[0.06] border-x border-primary/15">
                        <PricingV4Cell v={pv} highlight />
                      </div>
                    </div>
                  );
                })}
              </div>
            ))}

            {/* Footer row: CTA buttons aligned with each plan column */}
            <div className="grid grid-cols-[38%_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-x-2 items-center bg-card2/30">
              <div className="px-5 py-4 text-[14px] text-subtlefg">
                Ready to get started?
              </div>
              {PRICING_V4_PLANS.map((p) => (
                <div
                  key={p.id}
                  className={`px-3 py-4 ${
                    p.primary
                      ? "bg-primary/[0.06] border-x border-b border-primary/15 rounded-b-md"
                      : ""
                  }`}
                >
                  <a
                    href={pricingV4CheckoutHref(p, annual)}
                    className={`flex items-center justify-center gap-1.5 rounded-md py-2 text-[12.5px] font-semibold transition-colors ${
                      p.primary
                        ? "bg-primary text-primaryFg hover:brightness-110"
                        : "bg-card2 text-fg border border-border1 hover:border-primary/40 hover:text-primary"
                    }`}
                  >
                    {p.cta} {p.primary && <IcoArrowRight size={12} />}
                  </a>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ---------------- MOBILE: stacked cards ---------------- */}
      <div className="md:hidden space-y-6">
        {PRICING_V4_PLANS.map((plan, pi) => (
          <div key={plan.id}>
            <PricingV4PlanHeader plan={plan} annual={annual} />
            <div className="mt-3 rounded-xl border border-border1 bg-card/40 overflow-hidden">
              {PRICING_V4_GROUPS.map((group) => (
                <div key={group.title}>
                  <div className="px-4 py-2 text-[10px] font-semibold uppercase tracking-[0.16em] text-subtlefg bg-card2/60 border-b border-border2">
                    {group.title}
                  </div>
                  {group.rows.map((row, ri) => {
                    const v = row[pi + 1];
                    return (
                      <div
                        key={ri}
                        className={`flex items-center justify-between px-4 py-2.5 border-b border-border2/60 text-[13px] ${
                          v === false ? "opacity-60" : ""
                        }`}
                      >
                        <span className="text-mutedfg">{row[0]}</span>
                        <PricingV4Cell v={v} highlight={plan.primary} />
                      </div>
                    );
                  })}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Footnote — glued under the table */}
      <div className="mt-3 flex flex-wrap items-center justify-between gap-x-5 gap-y-1.5 text-[12px] text-subtlefg">
        <div className="flex flex-wrap items-center gap-x-5 gap-y-1.5">
          <span className="inline-flex items-center gap-1.5">
            <IcoCheck size={12} className="text-positive" /> All features unlocked
          </span>
          <span className="inline-flex items-center gap-1.5">
            <IcoCheck size={12} className="text-positive" /> No setup fee
          </span>
          <span className="inline-flex items-center gap-1.5">
            <IcoCheck size={12} className="text-positive" /> Cancel anytime
          </span>
        </div>
        <p className="md:text-right">
          <span className="text-primary">*</span> After your 15 day trial, your account becomes read-only until you pick a plan.
        </p>
      </div>
    </>
  );
}

function PricingV4() {
  return (
    <Section
      id="pricing"
      eyebrow="Pricing"
      title={<>Simple plans. <span className="text-primary">One price, no surprises.</span></>}
      sub="Start with a 15 day full-feature trial. Then pick Starter for core analytics, or Pro for the full systematic workflow."
    >
      <PricingV4Content />
    </Section>
  );
}

Object.assign(window, { PricingV4, PricingV4Content });
