<!DOCTYPE html>
<meta charset="utf-8">
<title>HTML Test: focus - the sequential focus navigation order with nested shadow dom with varying tabindex values</title>
<link rel="help" href="https://html.spec.whatwg.org/multipage/interaction.html#sequential-focus-navigation">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script src="resources/shadow-utils.js"></script>
<body>
<script>
promise_test(async () => {
  function createButtonInShadowDOM(host, parent) {
    const root = host.attachShadow({mode: "open"});
    root.innerHTML = "<input>";
    parent.appendChild(host);
    return root;
  }

  const host1 = document.createElement("div");
  const root1 = createButtonInShadowDOM(host1, document.body);

  const forwarder = document.createElement("div");
  forwarder.setAttribute("tabindex", 0);
  document.body.appendChild(forwarder);

  const host2 = document.createElement("div");
  host2.setAttribute("tabindex", -1);
  const root2 = host2.attachShadow({mode: "open"});
  document.body.appendChild(host2);

  const host2_1 = document.createElement("div");
  const root2_1 = createButtonInShadowDOM(host2_1, root2);

  const host2_2 = document.createElement("div");
  host2_2.setAttribute("tabindex", -1);
  const root2_2 = createButtonInShadowDOM(host2_2, root2);

  const host2_3 = document.createElement("div");
  const root2_3 = createButtonInShadowDOM(host2_3, root2);

  root1.querySelector("input").focus();

  let forwarderFocused = false;
  forwarder.addEventListener("focus", () => {
    forwarderFocused = true;
    root2_2.querySelector("input").focus();
  });

  // Structure:
  // <div #host1></div>
  //   #ShadowRoot
  //     <button>Button</button>
  // <div #forwarder tabindex=0></div>
  // <div #host2 tabindex=-1></div>
  //   #ShadowRoot
  //     <div #host2_1></div>
  //       #ShadowRoot
  //         <button>Button</button>
  //     <div #host2_2 tabindex=-1></div>
  //       #ShadowRoot
  //         <button>Button</button>
  //     <div #host2_3></div>
  //       #ShadowRoot
  //         <button>Button</button>
  assert_equals(document.activeElement, host1);
  assert_equals(root1.activeElement, root1.querySelector("input"));

  await navigateFocusForward();
  assert_true(forwarderFocused);
  assert_equals(document.activeElement, host2);
  assert_equals(root2_2.activeElement, root2_2.querySelector("input"));

  // In buggy Firefox build, the following focus navigation will
  // move the focus back to #host1_1's button.
  await navigateFocusForward();
  assert_equals(document.activeElement, host2);
  assert_equals(root2_3.activeElement, root2_3.querySelector("input"));
}, "Order with different tabindex on host")
</script>
