import { createUser } from "../../core/users.js";

const USER_SETUP_TEMPLATE = `
<section class="view user-setup-view" data-view="user-setup">
  <section class="user-setup-layout panel">
    <section class="user-setup-main">
      <p class="user-setup-eyebrow">First Time Setup</p>
      <h1 class="user-setup-title">Create Your Profile</h1>
      <p class="user-setup-copy">Use your controller to enter your first and last name, then press Done.</p>

      <div class="user-setup-fields">
        <div class="user-setup-field" data-field-card="firstName">
          <span class="user-setup-label">First Name</span>
          <p class="user-setup-value" data-field-value="firstName">-</p>
        </div>
        <div class="user-setup-field" data-field-card="lastName">
          <span class="user-setup-label">Last Name (Optional)</span>
          <p class="user-setup-value" data-field-value="lastName">-</p>
        </div>
      </div>

      <p class="user-setup-status" data-user-setup-status></p>
    </section>
  </section>
</section>
`;

export const createUserSetupView = ({ state, renderView, keyboard }) => {
  const model = {
    activeField: "firstName",
    firstName: "",
    lastName: "",
    busy: false,
  };

  const setStatus = (text = "", danger = false) => {
    const status = document.querySelector("[data-user-setup-status]");
    if (!status) {
      return;
    }
    status.textContent = text;
    status.classList.toggle("is-danger", danger);
  };

  const renderFields = () => {
    const firstValue = document.querySelector("[data-field-value='firstName']");
    const lastValue = document.querySelector("[data-field-value='lastName']");
    if (firstValue) {
      firstValue.textContent = model.firstName || "-";
    }
    if (lastValue) {
      lastValue.textContent = model.lastName || "-";
    }

    const firstCard = document.querySelector("[data-field-card='firstName']");
    const lastCard = document.querySelector("[data-field-card='lastName']");
    firstCard?.classList.toggle("is-active", model.activeField === "firstName");
    lastCard?.classList.toggle("is-active", model.activeField === "lastName");
  };

  const appendCharacter = (character) => {
    const field = model.activeField;
    const maxLength = 20;
    if (character === " ") {
      if (!model[field]) {
        return;
      }
      if (model[field].length >= maxLength) {
        return;
      }
      model[field] += " ";
      return;
    }
    if (model[field].length >= maxLength) {
      return;
    }
    model[field] += character;
  };

  const backspaceCharacter = () => {
    const field = model.activeField;
    if (!model[field]) {
      return;
    }
    model[field] = model[field].slice(0, -1);
  };

  const clearField = () => {
    model[model.activeField] = "";
  };

  const saveUser = async () => {
    if (model.busy) {
      return;
    }
    const firstName = model.firstName.trim();
    const lastName = model.lastName.trim();
    if (!firstName) {
      setStatus("First name is required.", true);
      return;
    }

    model.busy = true;
    setStatus("Creating profile...");
    try {
      const user = await createUser({ firstName, lastName });
      if (!user) {
        throw new Error("Could not create user.");
      }
      state.user = user;
      state.profileName = user.name;
      state.userSetupRequired = false;
      // New profile creation should always start with a fresh passkey setup.
      // This avoids inheriting stale passkey state from previous local data.
      state.passkey.resetSequence();
      state.passkeySetupRequired = true;
      state.activeView = "lock";
      keyboard.close();
      renderView("lock");
    } catch (error) {
      setStatus(error?.message ?? "Failed to create user.", true);
    } finally {
      model.busy = false;
    }
  };

  const selectField = (field) => {
    model.activeField = field;
    renderFields();
  };

  const nextField = () => {
    selectField(model.activeField === "firstName" ? "lastName" : "firstName");
    setStatus(`Editing ${model.activeField === "firstName" ? "First Name" : "Last Name"}.`);
  };

  const prevField = () => {
    nextField();
  };

  return {
    id: "user-setup",
    render: () => USER_SETUP_TEMPLATE,
    mount: () => {
      if (!state.userSetupRequired) {
        keyboard.close();
        renderView("lock");
        return;
      }
      model.activeField = "firstName";
      model.firstName = "";
      model.lastName = "";
      model.busy = false;
      renderFields();
      keyboard.open({
        onKey: (key) => {
          appendCharacter(key);
          renderFields();
          setStatus("");
        },
        onBackspace: () => {
          backspaceCharacter();
          renderFields();
          setStatus("");
        },
        onClear: () => {
          clearField();
          renderFields();
          setStatus("");
        },
        onSubmit: () => {
          saveUser();
        },
        onPrevField: () => {
          prevField();
        },
        onNextField: () => {
          nextField();
        },
      });
      setStatus("Enter first name, then press Enter or Menu.");
    },
    getNavigationContract: () => {
      return {
        focusRoot: null,
        defaultFocus: null,
        layout: { type: "grid", cols: 1, rows: 1 },
        hintsTemplate: "#keyboard-hints-template",
        nebulaNavigation: state.nebula.navigation,
        captureDirectionalInput: false,
        onAccept: () => {},
        onBack: () => {
          keyboard.handleAction("back");
        },
        onMenu: () => {
          keyboard.handleAction("menu");
          return false;
        },
        onAction: () => false,
      };
    },
  };
};
