/* global ABTESTKIT_ONBOARDING, wp */
(function () {
  const { createElement: h, useState } = wp.element;
  const { Button, Card, CardBody, Notice, Spinner, RadioControl } = wp.components;
  const apiFetch = wp.apiFetch;

  // Wire the REST nonce
  apiFetch.use(apiFetch.createNonceMiddleware(ABTESTKIT_ONBOARDING.nonce));

  // Small helper to get an asset URL safely
  function getAsset(key) {
    if (
      ABTESTKIT_ONBOARDING.assets &&
      Object.prototype.hasOwnProperty.call(ABTESTKIT_ONBOARDING.assets, key)
    ) {
      return ABTESTKIT_ONBOARDING.assets[key];
    }
    return null;
  }

  function Step1CreateTest({ next }) {
    // Reuse your existing asset keys if they exist
    const img =
      getAsset("getStarted") ||
      getAsset("selectTestType") ||
      getAsset("summary") ||
      null;

    return h(
      Card,
      { className: "abtestkit-card" },
      h(
        CardBody,
        null,
        h("h2", { style: { marginTop: 0 } }, "Create your first test"),
        h(
          "p",
          { style: { marginBottom: 12 } },
          "Click 'Create New Test+' from the Sidebar or Dashboard. From here you'll follow the Test Creator to:",
        ),
        h(
          "ul",
          { style: { marginTop: 0, paddingLeft: "1.2em" } },
          h(
            "li",
            null,
            h("strong", null, "Pick a test type"),
            " (Page, Post, or WooCommerce Product).",
          ),
          h(
            "li",
            null,
            h("strong", null, "Create Version B"),
            " (either a copy or an existing page).",
          ),
          h(
            "li",
            null,
            h("strong", null, "Choose a conversion"),
            " (Forms, Add to Cart, or Click targets).",
          ),
        ),
        img &&
          h("div", { style: { marginTop: 16, marginBottom: 16 } }, [
            h("img", {
              src: img,
              alt: "abtestkit create test wizard",
              style: {
                display: "block",
                maxWidth: "100%",
                height: "auto",
                borderRadius: 10,
              },
            }),
          ]),
        h(
          Notice,
          {
            status: "info",
            isDismissible: false,
            style: { marginTop: 8 },
          },
          h(
            "div",
            { style: { lineHeight: 1.5 } },
            h("strong", null, "Pro tip:"),
            " if you’re logged into WordPress, you will only see Version A. That’s intentional - admins don’t affect results.",
          ),
        ),
        h(
          "div",
          { style: { marginTop: 16, textAlign: "right" } },
          h(
            Button,
            { variant: "primary", onClick: next },
            "Next: How winners are picked",
          ),
        ),
      ),
    );
  }

  function Step2HowWinnersWork({ next, back }) {
    const img = getAsset("dashboard") || null;

    return h(
      Card,
      { className: "abtestkit-card" },
      h(
        CardBody,
        null,
        h("h2", { style: { marginTop: 0 } }, "How winners are picked"),
        img &&
          h("div", { style: { marginBottom: 12 } }, [
            h("img", {
              src: img,
              alt: "abtestkit dashboard results",
              style: {
                display: "block",
                maxWidth: "100%",
                height: "auto",
                borderRadius: 10,
              },
            }),
          ]),
        h(
          "p",
          { style: { marginBottom: 12 } },
          "abtestkit can automatically declare a winner when there is strong evidence one version is performing better - so you don’t have to guess.",
        ),
        h(
          "ul",
          { style: { marginTop: 0, paddingLeft: "1.2em" } },
          h(
            "li",
            null,
            h("strong", null, "Random split"),
            ": visitors are assigned Version A or B and kept consistent using a cookie.",
          ),
          h(
            "li",
            null,
            h("strong", null, "Minimum data"),
            ": tests require a minimum sample before a winner can be declared (e.g. impressions/conversions thresholds).",
          ),
          h(
            "li",
            null,
            h("strong", null, "Winning threshold"),
            ": For automatic testing, you decide how confident the algorithm needs to be to declare a winner.",
          ),
        ),
        h(
          Notice,
          {
            status: "info",
            isDismissible: false,
            style: { marginTop: 16 },
          },
          h(
            "ul",
            { style: { margin: 0, paddingLeft: "1.2em" } },
            h(
              "li",
              null,
              "To keep the data clean, logged-in admins are excluded from tracking.",
            ),
            h(
              "li",
              null,
              "Only one impression/click is recorded per visitor per session (to reduce spammy inflation).",
            ),
          ),
        ),
        h(
          "div",
          {
            style: {
              marginTop: 16,
              display: "flex",
              justifyContent: "space-between",
              gap: 8,
            },
          },
          h(Button, { variant: "secondary", onClick: back }, "Back"),
          h(
            Button,
            { variant: "primary", onClick: next },
            "Next: You’re ready",
          ),
        ),
      ),
    );
  }

  function Step3Ready({ back, finish, telemetryChoice, setTelemetryChoice }) {
    const canFinish = telemetryChoice === "yes" || telemetryChoice === "no";

    return h(
      Card,
      { className: "abtestkit-card" },
      h(
        CardBody,
        null,
        h("h2", { style: { marginTop: 0 } }, "You’re ready"),
        h(
          "p",
          { style: { marginBottom: 12 } },
          "The fastest way to learn abtestkit is to run your first test. Start with a small change (headline, CTA text, button placement) and let the results guide you.",
        ),
        h(
          "ul",
          { style: { marginTop: 0, paddingLeft: "1.2em" } },
          h("li", null, "Create a test from the WordPress sidebar (abtestkit → Create New Test +)."),
          h("li", null, "Let it collect data - don’t call it early."),
          h("li", null, "Ship the winner and run the next test."),
        ),

        h(
          "div",
          {
            style: {
              marginTop: 16,
              padding: 12,
              border: "1px solid rgba(0,0,0,0.08)",
              borderRadius: 10,
            },
          },
          h("h3", { style: { margin: "0 0 8px 0" } }, "Help improve abtestkit"),
          h(
            "p",
            { style: { margin: "0 0 12px 0", lineHeight: 1.5 } },
            "We're dedicated to helping you optimize your store, share the love?",
          ),
          h(RadioControl, {
            label: "Anonymous telemetry",
            selected: telemetryChoice || "",
            options: [
              { label: "Yes - I'm happy to help", value: "yes" },
              { label: "No.", value: "no" },
            ],
            onChange: (v) => setTelemetryChoice(v),
          }),
        ),

        h(
          Notice,
          {
            status: "success",
            isDismissible: false,
            style: { marginTop: 16 },
          },
          h(
            "div",
            { style: { lineHeight: 1.5 } },
            h("strong", null, "Your privacy: "),
            "abtestkit keeps all your data safe on your site. Telemetry only sends anonymous usage data.",
          ),
        ),

        h(
          "div",
          {
            style: {
              marginTop: 16,
              display: "flex",
              justifyContent: "space-between",
              gap: 8,
            },
          },
          h(Button, { variant: "secondary", onClick: back }, "Back"),
          h(
            Button,
            { variant: "primary", onClick: finish, disabled: !canFinish },
            "Create first test +",
          ),
        ),
      ),
    );
  }

  function WizardApp() {
    const [step, setStep] = useState(0);
    const [busy, setBusy] = useState(false);

    const initialTelemetryChoice =
      ABTESTKIT_ONBOARDING &&
      typeof ABTESTKIT_ONBOARDING.telemetryOptedIn === "boolean"
        ? (ABTESTKIT_ONBOARDING.telemetryOptedIn ? "yes" : "no")
        : null;

    const [telemetryChoice, setTelemetryChoice] = useState(initialTelemetryChoice);

    const finish = async () => {
      try {
        setBusy(true);
        await apiFetch({
          path: "/abtestkit/v1/onboarding",
          method: "POST",
          data: {
            done: true,
            telemetry: telemetryChoice === "yes",
          },
        });
      } catch (e) {
        // Non-fatal, just continue
      } finally {
        setBusy(false);
        window.location =
          (ABTESTKIT_ONBOARDING.links && ABTESTKIT_ONBOARDING.links.createUrl)
            ? ABTESTKIT_ONBOARDING.links.createUrl
            : ((window.abtestkitDashboard && abtestkitDashboard.createUrl)
                ? abtestkitDashboard.createUrl
                : ABTESTKIT_ONBOARDING.links.plugins);
      }
    };

    const titles = ["Create a test", "How winners work", "You’re ready"];

    return h(
      "div",
      {
        className: "abtestkit-onboarding-page",
        style: {
          position: "relative",
          maxWidth: 900,
          margin: "32px auto",
        },
      },
      busy &&
        h(
          "div",
          {
            style: {
              position: "absolute",
              inset: 0,
              display: "grid",
              placeItems: "center",
              background: "rgba(255,255,255,0.6)",
              zIndex: 10,
              borderRadius: 12,
            },
          },
          h(Spinner),
        ),
      h(
        "div",
        {
          style: {
            display: "flex",
            justifyContent: "space-between",
            alignItems: "baseline",
            marginBottom: 16,
          },
        },
        h("h1", { style: { margin: 0 } }, "Welcome to abtestkit 👋"),
        h(
          "div",
          {
            style: {
              fontSize: 12,
              opacity: 0.8,
            },
          },
          "Step ",
          step + 1,
          " of ",
          titles.length,
          " – ",
          titles[step],
        ),
      ),
      step === 0 && h(Step1CreateTest, { next: () => setStep(1) }),
      step === 1 &&
        h(Step2HowWinnersWork, {
          next: () => setStep(2),
          back: () => setStep(0),
        }),
      step === 2 &&
        h(Step3Ready, {
          back: () => setStep(1),
          finish,
          telemetryChoice,
          setTelemetryChoice,
        }),
    );
  }

  // Mount
  document.addEventListener("DOMContentLoaded", () => {
    // If onboarding already completed, don’t show this screen again.
    if (
      ABTESTKIT_ONBOARDING &&
      ABTESTKIT_ONBOARDING.done &&
      ABTESTKIT_ONBOARDING.links &&
      ABTESTKIT_ONBOARDING.links.dashboard
    ) {
      window.location = ABTESTKIT_ONBOARDING.links.dashboard;
      return;
    }

    const root = document.getElementById("abtestkit-onboarding-root");
    if (root) {
      wp.element.render(h(WizardApp), root);
    }
  });
})();