/**
 * ProfilePage — real My Profile form, wired to backend.
 * Supports all 13 roles. Tabs: Basic Info · Documents.
 * User fills and saves freely; "Submit for Verification" locks and queues for admin.
 */
import { For, Match, Show, Switch, createEffect, createMemo, createSignal, onMount } from "solid-js";
import {
  CARD,
  BTN_GHOST,
  INPUT,
  LABEL,
  BTN_PRIMARY,
} from "~/components/DashboardShell";
import {
  isValidEmail,
  isValidName,
  isValidPhone,
  isValidTitle,
  isValidLocation,
  isValidURL,
} from "~/lib/form-validation";
import { request, uploadDocument, submitCompanyProfileWithDocuments } from "~/lib/api";
import {
  getBasicFields,
  getDocFields,
  // BASIC_FIELDS and DOC_FIELDS are imported indirectly via the accessors above.
  // Re-export them for backward-compatibility with local applyRuntimeFields:
  type BasicField,
  type DocField,
} from "~/lib/profile-fields-config";
import { fetchOnboardingSchemaForRole } from "~/lib/runtime/storage";
import RoleWizard from "~/components/dashboard/RoleWizard";

// The K8s ingress routes /api/* directly to the Rust gateway service in
// production — there is no /api/gateway rewrite layer, so paths below are
// hit as-is (each apiFetch() call already passes a fully-qualified /api/... path).
const API = "";

const PORTFOLIO_PREFIX: Record<string, string> = {
  PHOTOGRAPHER: "photographers",
  MAKEUP_ARTIST: "makeup-artists",
  TUTOR: "tutors",
  DEVELOPER: "developers",
  VIDEO_EDITOR: "video-editors",
  GRAPHIC_DESIGNER: "graphic-designers",
  SOCIAL_MEDIA_MANAGER: "social-media-managers",
  FITNESS_TRAINER: "fitness-trainers",
  CATERING_SERVICES: "catering-services",
  UGC_CONTENT_CREATOR: "ugc-content-creators",
};

// BASIC_FIELDS and DOC_FIELDS are now sourced from profile-fields-config.ts.
// PORTFOLIO_PREFIX maps professional roles to their portfolio API prefix.
function applyRuntimeFields<T extends { key: string }>(fields: T[], runtimeFields?: string[]): T[] {
  if (!runtimeFields || runtimeFields.length === 0) return fields;
  const fieldMap = new Map(fields.map(f => [f.key, f]));
  return runtimeFields
    .filter(key => fieldMap.has(key))
    .map(key => fieldMap.get(key)!);
}

function resolveRuntimeFieldKeys(runtimeFields?: string[]): string[] {
  if (!runtimeFields || runtimeFields.length === 0) return [];
  const FIELD_KEY_MAP: Record<string, string> = {
    full_name: 'first_name',
    email: 'email',
    phone: 'phone',
    location: 'city',
    verification_status: '',
    approval_status: '',
  };
  const resolved: string[] = [];
  for (const key of runtimeFields) {
    const mapped = FIELD_KEY_MAP[key];
    if (mapped) resolved.push(mapped);
  }
  return resolved;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== "undefined"
      ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
      : "";
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

// ── Component ─────────────────────────────────────────────────────────────────

interface Props {
  roleKey: string;
  runtimeFields?: string[];
  onVerificationStatusChange?: (status: string) => void;
  onNavigate?: (key: string) => void;
}

type Tab = "basic" | "documents";

// ── CompanyWizard — 3-step verification wizard for COMPANY role ──────────────
interface CompanyWizardProps {
  wizardStep: () => number;
  setWizardStep: (s: number | ((prev: number) => number)) => void;
  wizardDocs: () => Record<string, File>;
  setWizardDocs: (
    s: Record<string, File> | ((prev: Record<string, File>) => Record<string, File>)
  ) => void;
  wizardDocErrors: () => Record<string, string>;
  setWizardDocErrors: (
    s: Record<string, string> | ((prev: Record<string, string>) => Record<string, string>)
  ) => void;
  wizardSubmitting: () => boolean;
  wizardSubmitMsg: () => string;
  wizardSubmitSuccess: () => boolean;
  wizardCanAdvance: () => boolean;
  handleWizardSubmit: () => void;
  form: () => Record<string, string>;
  setField: (key: string, val: string) => void;
  basicFields: () => Array<{
    key: string;
    label: string;
    type?: string;
    required?: boolean;
    options?: string[];
  }>;
  getDocFields: (roleKey: string) => Array<{
    key: string;
    label: string;
    required?: boolean;
    hint?: string;
  }>;
  fieldNote: (
    key: string,
    label: string,
    required: boolean,
    fieldType?: string
  ) => any;
  wizardReset: () => void;
}

function CompanyWizard(props: CompanyWizardProps) {
  const stepLabels = ["Basic Information", "Documents", "Review & Submit"];

  const formatBytes = (n: number) => {
    if (n < 1024) return `${n} B`;
    if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
    return `${(n / (1024 * 1024)).toFixed(1)} MB`;
  };

  return (
    <div>
      {/* ── Success card ─────────────────────────────────────────────── */}
      <Show when={props.wizardSubmitSuccess()}>
        <div
          style={{
            ...CARD,
            "margin-bottom": "16px",
            padding: "24px",
            background: "#ECFDF5",
            border: "1px solid #6EE7B7",
            "text-align": "center",
          }}
        >
          <div style={{ "font-size": "36px", "margin-bottom": "8px" }}>✓</div>
          <h3 style={{ margin: "0 0 8px", "font-size": "18px", color: "#065F46" }}>
            Submitted!
          </h3>
          <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#065F46" }}>
            We'll review your profile and notify you within 24–48 hours.
          </p>
          <button
            type="button"
            onClick={() => {
              if (typeof window !== "undefined") window.location.reload();
            }}
            style={{ ...BTN_PRIMARY }}
          >
            View Dashboard
          </button>
        </div>
      </Show>

      <Show when={!props.wizardSubmitSuccess()}>
        {/* ── Stepper ────────────────────────────────────────────────── */}
        <div
          style={{
            display: "flex",
            "align-items": "center",
            gap: "8px",
            "margin-bottom": "24px",
          }}
        >
          <For each={[0, 1, 2]}>
            {(i) => (
              <>
                <div
                  style={{
                    width: "32px",
                    height: "32px",
                    "border-radius": "50%",
                    display: "flex",
                    "align-items": "center",
                    "justify-content": "center",
                    "font-weight": "700",
                    "font-size": "14px",
                    background:
                      props.wizardStep() === i
                        ? "#FF5E13"
                        : props.wizardStep() > i
                        ? "#FFF"
                        : "#F3F4F6",
                    color:
                      props.wizardStep() === i
                        ? "#FFF"
                        : props.wizardStep() > i
                        ? "#FF5E13"
                        : "#9CA3AF",
                    border:
                      props.wizardStep() >= i
                        ? "2px solid #FF5E13"
                        : "2px solid #E5E7EB",
                  }}
                >
                  {props.wizardStep() > i ? "✓" : i + 1}
                </div>
                <Show when={i < 2}>
                  <div
                    style={{
                      flex: 1,
                      height: "2px",
                      background: props.wizardStep() > i ? "#FF5E13" : "#E5E7EB",
                    }}
                  />
                </Show>
              </>
            )}
          </For>
        </div>
        <p
          style={{
            "font-size": "13px",
            color: "#6B7280",
            "margin-bottom": "16px",
          }}
        >
          Step {props.wizardStep() + 1} of 3 — {stepLabels[props.wizardStep()]}
        </p>

        {/* ── Step body ─────────────────────────────────────────────── */}
        <div style={CARD}>
          <Show when={props.wizardStep() === 0}>
            <h3 style={{ margin: "0 0 4px", "font-size": "15px", color: "#111827" }}>
              Tell us about your company
            </h3>
            <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#6B7280" }}>
              Fill in your company details to get started.
            </p>
            <div style={{ display: "grid", "grid-template-columns": "1fr 1fr", gap: "10px" }}>
              <For each={props.basicFields()}>
                {(field) => (
                  <div style={{ "grid-column": field.type === "textarea" ? "span 2" : "span 1" }}>
                    <label style={LABEL}>
                      {field.label}
                      <Show when={field.required}>
                        <span style={{ color: "#EF4444" }}> *</span>
                      </Show>
                    </label>
                    <Switch>
                      <Match when={field.type === "textarea"}>
                        <textarea
                          rows={3}
                          value={props.form()[field.key] ?? ""}
                          onInput={(e) => props.setField(field.key, e.currentTarget.value)}
                          style={{
                            ...INPUT,
                            height: "auto",
                            padding: "10px 12px",
                            resize: "vertical",
                          }}
                        />
                      </Match>
                      <Match when={field.type === "select"}>
                        <select
                          value={props.form()[field.key] ?? ""}
                          onChange={(e) => props.setField(field.key, e.currentTarget.value)}
                          style={{ ...INPUT }}
                        >
                          <option value="">Select…</option>
                          <For each={field.options ?? []}>
                            {(opt) => <option value={opt}>{opt}</option>}
                          </For>
                        </select>
                      </Match>
                      <Match when={true}>
                        <input
                          type={field.type ?? "text"}
                          value={props.form()[field.key] ?? ""}
                          onInput={(e) => props.setField(field.key, e.currentTarget.value)}
                          style={{ ...INPUT }}
                        />
                      </Match>
                    </Switch>
                    {props.fieldNote(field.key, field.label, !!field.required, field.type)}
                  </div>
                )}
              </For>
            </div>
          </Show>

          <Show when={props.wizardStep() === 1}>
            <h3 style={{ margin: "0 0 4px", "font-size": "15px", color: "#111827" }}>
              Upload your verification documents
            </h3>
            <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#6B7280" }}>
              We need to verify your business. Upload the following:
            </p>
            <div style={{ display: "flex", "flex-direction": "column", gap: "16px" }}>
              <For each={props.getDocFields("COMPANY")}>
                {(doc) => (
                  <div
                    style={{
                      border: "1px dashed #E5E7EB",
                      "border-radius": "10px",
                      padding: "16px",
                    }}
                  >
                    <p
                      style={{
                        margin: "0",
                        "font-size": "13px",
                        "font-weight": "700",
                        color: "#111827",
                      }}
                    >
                      {doc.label}
                      <Show when={doc.required}>
                        <span style={{ color: "#EF4444" }}> *</span>
                      </Show>
                    </p>
                    <Show when={doc.hint}>
                      <p style={{ margin: "2px 0 10px", "font-size": "11px", color: "#9CA3AF" }}>
                        {doc.hint}
                      </p>
                    </Show>
                    <Show
                      when={props.wizardDocs()[doc.key]}
                      fallback={
                        <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                          <input
                            type="file"
                            id={`wiz-file-${doc.key}`}
                            style={{ display: "none" }}
                            onChange={(e) => {
                              const file = e.currentTarget.files?.[0];
                              if (!file) return;
                              props.setWizardDocs((prev) => ({ ...prev, [doc.key]: file }));
                              props.setWizardDocErrors((prev) => ({ ...prev, [doc.key]: "" }));
                              e.currentTarget.value = "";
                            }}
                          />
                          <label
                            for={`wiz-file-${doc.key}`}
                            style={{
                              ...BTN_GHOST,
                              display: "inline-flex",
                              "align-items": "center",
                              "line-height": "1",
                              cursor: "pointer",
                            }}
                          >
                            Choose File
                          </label>
                          <span style={{ "font-size": "12px", color: "#9CA3AF" }}>
                            No file chosen
                          </span>
                        </div>
                      }
                    >
                      <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                        <span
                          style={{
                            "font-size": "12px",
                            "font-weight": "600",
                            color: "#10B981",
                            background: "#ECFDF5",
                            padding: "4px 10px",
                            "border-radius": "6px",
                          }}
                        >
                          ✓ {props.wizardDocs()[doc.key].name} ({formatBytes(props.wizardDocs()[doc.key].size)})
                        </span>
                        <button
                          type="button"
                          onClick={() => {
                            props.setWizardDocs((prev) => {
                              const next = { ...prev };
                              delete next[doc.key];
                              return next;
                            });
                          }}
                          style={{
                            ...BTN_GHOST,
                            height: "28px",
                            "font-size": "11px",
                            padding: "0 10px",
                          }}
                        >
                          Remove
                        </button>
                      </div>
                    </Show>
                    <Show when={props.wizardDocErrors()[doc.key]}>
                      <p style={{ margin: "4px 0 0", "font-size": "11px", color: "#EF4444" }}>
                        {props.wizardDocErrors()[doc.key]}
                      </p>
                    </Show>
                  </div>
                )}
              </For>
            </div>
          </Show>

          <Show when={props.wizardStep() === 2}>
            <h3 style={{ margin: "0 0 4px", "font-size": "15px", color: "#111827" }}>
              Review your information
            </h3>
            <p style={{ margin: "0 0 16px", "font-size": "13px", color: "#6B7280" }}>
              Please confirm everything looks correct before submitting.
            </p>
            <div
              style={{
                padding: "16px",
                background: "#F9FAFB",
                "border-radius": "8px",
                "margin-bottom": "16px",
              }}
            >
              <For each={props.basicFields()}>
                {(field) => (
                  <p style={{ margin: "4px 0", "font-size": "13px", color: "#374151" }}>
                    <strong>{field.label}:</strong>{" "}
                    {String(props.form()[field.key] || "").trim() || (
                      <span style={{ color: "#9CA3AF" }}>—</span>
                    )}
                  </p>
                )}
              </For>
            </div>
            <div
              style={{
                padding: "16px",
                background: "#F9FAFB",
                "border-radius": "8px",
              }}
            >
              <p style={{ margin: "0 0 6px", "font-size": "13px", "font-weight": "700", color: "#111827" }}>
                Documents:
              </p>
              <For each={props.getDocFields("COMPANY")}>
                {(doc) => {
                  const f = props.wizardDocs()[doc.key];
                  return (
                    <p style={{ margin: "2px 0", "font-size": "12px", color: "#374151" }}>
                      <strong>{doc.label}:</strong>{" "}
                      {f ? `${f.name} (${formatBytes(f.size)})` : <span style={{ color: "#9CA3AF" }}>—</span>}
                    </p>
                  );
                }}
              </For>
            </div>
          </Show>

          {/* ── Navigation buttons ──────────────────────────────────── */}
          <div
            style={{
              display: "flex",
              "justify-content": "space-between",
              "margin-top": "24px",
            }}
          >
            <button
              type="button"
              onClick={() => props.setWizardStep((s) => s - 1)}
              disabled={props.wizardStep() === 0}
              style={{ ...BTN_GHOST, opacity: props.wizardStep() === 0 ? 0.5 : 1 }}
            >
              Back
            </button>
            <Show
              when={props.wizardStep() < 2}
              fallback={
                <button
                  type="button"
                  onClick={props.handleWizardSubmit}
                  disabled={props.wizardSubmitting()}
                  style={{ ...BTN_PRIMARY, opacity: props.wizardSubmitting() ? 0.7 : 1 }}
                >
                  {props.wizardSubmitting() ? "Submitting..." : "Submit for Verification"}
                </button>
              }
            >
              <button
                type="button"
                onClick={() => props.setWizardStep((s) => s + 1)}
                disabled={!props.wizardCanAdvance()}
                style={{
                  ...BTN_PRIMARY,
                  opacity: props.wizardCanAdvance() ? 1 : 0.5,
                }}
              >
                Next
              </button>
            </Show>
          </div>

          <Show when={props.wizardSubmitMsg() && props.wizardStep() === 2}>
            <div
              style={{
                "margin-top": "12px",
                padding: "10px 14px",
                background: "#FEF2F2",
                border: "1px solid #FECACA",
                color: "#B91C1C",
                "font-size": "13px",
                "font-weight": "600",
                "border-radius": "6px",
              }}
            >
              {props.wizardSubmitMsg()}
            </div>
          </Show>
        </div>
      </Show>
    </div>
  );
}

export default function ProfilePage(props: Props) {
  const [tab, setTab] = createSignal<Tab>("basic");
  const [form, setForm] = createSignal<Record<string, string>>({});
  const [saving, setSaving] = createSignal(false);
  const [saveMsg, setSaveMsg] = createSignal("");
  const [verificationStatus, setVerificationStatus] = createSignal("NOT_SUBMITTED");
  const [docRequest, setDocRequest] = createSignal<string | null>(null);
  const [docUrls, setDocUrls] = createSignal<Record<string, string>>({});
  const [docUploadErrors, setDocUploadErrors] = createSignal<Record<string, string>>({});
  const [submitting, setSubmitting] = createSignal(false);
  const [submitMsg, setSubmitMsg] = createSignal("");
  const [missingPortfolioLabels, setMissingPortfolioLabels] = createSignal<string[]>([]);
  const [avatarUrl, setAvatarUrl] = createSignal<string>("");
  const [photoUploading, setPhotoUploading] = createSignal(false);
  const [photoMsg, setPhotoMsg] = createSignal("");

  // ── Wizard state (COMPANY role only) ────────────────────────────────────
  const [wizardStep, setWizardStep] = createSignal(0);
  const [wizardDocs, setWizardDocs] = createSignal<Record<string, File>>({});
  const [wizardDocErrors, setWizardDocErrors] = createSignal<Record<string, string>>({});
  const [wizardSubmitting, setWizardSubmitting] = createSignal(false);
  const [wizardSubmitMsg, setWizardSubmitMsg] = createSignal("");
  const [wizardSubmitSuccess, setWizardSubmitSuccess] = createSignal(false);

  // ── Runtime onboarding config: wizard-vs-tabs + per-field post-approval lock ──
  // Admin-configurable via the Onboarding Schema Editor (onboarding_configs
  // table) — nothing here is hardcoded per role.
  const [wizardEnabled, setWizardEnabled] = createSignal(false);
  const [lockedFieldIds, setLockedFieldIds] = createSignal<Set<string>>(new Set());

  const isCompany = () => props.roleKey === "COMPANY";

  const rolePrefix = () =>
    props.roleKey === "JOB_SEEKER"
      ? "jobseeker"
      : props.roleKey === "COMPANY"
        ? "companies"
        : props.roleKey === "CATERING_SERVICES"
          ? "catering-services"
          : props.roleKey.toLowerCase().replace(/_/g, "-") + "s";

  // Statuses during which the guided wizard (rather than free-form tabs)
  // should be shown: first-time setup, or the admin sent it back for fixes.
  const WIZARD_STATUSES = ["NOT_SUBMITTED", "DOCUMENTS_REQUESTED", "REVISION_REQUESTED", "REJECTED"];
  const showWizard = () => wizardEnabled() && WIZARD_STATUSES.includes(verificationStatus());

  // A field is permanently locked once the profile has ever been approved,
  // if the active onboarding schema marked it lockAfterApproval — enforced
  // server-side too (apps/users/src/handlers/profile.rs), this just keeps
  // the UI honest about it.
  const fieldLocked = (key: string) => isLocked() || (verificationStatus() === "APPROVED" && lockedFieldIds().has(key));

  const requiresPortfolio = () => props.roleKey === "JOB_SEEKER" || Boolean(PORTFOLIO_PREFIX[props.roleKey]);

  const refreshPortfolioSubmission = async (): Promise<string[]> => {
    if (props.roleKey === "JOB_SEEKER") {
      const missing: string[] = [];
      try {
        const res = await apiFetch("/api/jobseeker/profile/me");
        if (!res.ok) {
          setMissingPortfolioLabels(["Portfolio details"]);
          return ["Portfolio details"];
        }
        const data = await res.json().catch(() => ({}));
        const portfolio = data?.custom_data?.job_seeker_portfolio || {};
        if (!String(portfolio?.headline || "").trim()) missing.push("Professional headline");
        if (!String(portfolio?.summary || "").trim()) missing.push("Career summary");
        if (!String(portfolio?.education || "").trim()) missing.push("Education");
        if (!String(portfolio?.workExperience || "").trim()) missing.push("Work experience");
        if (!String(portfolio?.skills || "").trim()) missing.push("Skills");
      } catch {
        missing.push("Portfolio details");
      }
      setMissingPortfolioLabels(missing);
      return missing;
    }

    if (!requiresPortfolio()) {
      setMissingPortfolioLabels([]);
      return [];
    }

    const missing: string[] = [];
    const roleStorageKey = `nxtgauge_portfolio_meta_${String(props.roleKey || "professional").toLowerCase()}`;

    let meta: any = {};
    if (typeof window !== "undefined") {
      try {
        const raw = window.localStorage.getItem(roleStorageKey);
        meta = raw ? JSON.parse(raw) : {};
      } catch {
        meta = {};
      }
    }

    const aboutDone = String(meta?.about || "").trim().length > 0;
    const servicesDone = Array.isArray(meta?.services)
      ? meta.services.some((s: any) =>
          String(s?.name || "").trim() || String(s?.amount || "").trim() || String(s?.details || "").trim()
        )
      : false;
    const experienceDone = Array.isArray(meta?.experience)
      ? meta.experience.some((e: any) => String(e?.year || "").trim() || String(e?.description || "").trim())
      : false;
    const toolsDone = Array.isArray(meta?.tools) ? meta.tools.some((t: any) => String(t || "").trim()) : false;
    const faqDone = Array.isArray(meta?.faqs)
      ? meta.faqs.some((f: any) => String(f?.question || "").trim() && String(f?.answer || "").trim())
      : false;

    if (!aboutDone) missing.push("About");
    if (!servicesDone) missing.push("Services & pricing");
    if (!experienceDone && !toolsDone) missing.push("Experience / tools");
    if (!faqDone) missing.push("FAQs");

    try {
      const res = await apiFetch(`/api/${PORTFOLIO_PREFIX[props.roleKey]}/portfolio/me`);
      if (!res.ok) {
        missing.push("Showcase items");
        setMissingPortfolioLabels(Array.from(new Set(missing)));
        return Array.from(new Set(missing));
      }
      const data = await res.json().catch(() => []);
      const items = Array.isArray(data) ? data : data?.items ?? data?.data ?? [];
      if (!Array.isArray(items) || items.length === 0) missing.push("Showcase items");
    } catch {
      missing.push("Showcase items");
    }

    const uniqueMissing = Array.from(new Set(missing));
    setMissingPortfolioLabels(uniqueMissing);
    return uniqueMissing;
  };

  // Load saved profile + verification status on mount
  onMount(async () => {
    void fetchOnboardingSchemaForRole(props.roleKey).then((cfg) => {
      if (!cfg) return;
      setWizardEnabled(Boolean(cfg.enableWizardFlow));
      const locked = new Set<string>();
      for (const step of cfg.steps) {
        for (const field of step.fields) {
          if (field.lockAfterApproval) locked.add(field.id);
        }
      }
      setLockedFieldIds(locked);
    });

    const [profileRes, statusRes] = await Promise.all([
      apiFetch(`/api/profile?roleKey=${props.roleKey}`),
      apiFetch(`/api/me/verification-status?roleKey=${props.roleKey}`),
    ]);

    if (profileRes.ok) {
      const data = await profileRes.json();
      if (data.profile_data && typeof data.profile_data === "object") {
        const flat: Record<string, string> = {};
        for (const [k, v] of Object.entries(data.profile_data)) {
          flat[k] = String(v ?? "");
        }
        setForm(flat);

        // Documents are saved into the same profile_data blob as basic fields —
        // pull out whichever doc keys this role expects so previously uploaded
        // files show as already-attached instead of appearing lost on reload.
        const docKeys = getDocFields(props.roleKey).map((d) => d.key);
        const savedDocs: Record<string, string> = {};
        for (const key of docKeys) {
          const val = data.profile_data[key];
          if (typeof val === "string" && val) savedDocs[key] = val;
        }
        if (Object.keys(savedDocs).length > 0) setDocUrls((prev) => ({ ...savedDocs, ...prev }));
      }
    }

    if (props.roleKey === "JOB_SEEKER") {
      try {
        const docsRes = await apiFetch("/api/jobseeker/profile/documents");
        if (docsRes.ok) {
          const docsPayload = await docsRes.json().catch(() => ({}));
          const docs = Array.isArray(docsPayload?.data) ? docsPayload.data : [];
          const savedDocs: Record<string, string> = {};
          for (const doc of docs) {
            const key = String(doc?.document_type || "").trim();
            const url = String(doc?.file_url || "").trim();
            if (key && url) savedDocs[key] = url;
          }
          if (Object.keys(savedDocs).length > 0) {
            setDocUrls((prev) => ({ ...savedDocs, ...prev }));
          }
        }
      } catch {
        // Best-effort rehydration only.
      }
    }

    if (statusRes.ok) {
      const s = await statusRes.json();
      const nextStatus = String(s.status ?? "NOT_SUBMITTED");
      setVerificationStatus(nextStatus);
      props.onVerificationStatusChange?.(nextStatus);
      setDocRequest(s.document_request ?? null);
    }

    // Load existing avatar
    try {
      const meRes = await apiFetch("/api/me");
      if (meRes.ok) {
        const me = await meRes.json().catch(() => ({}));
        if (me?.avatar_url) setAvatarUrl(String(me.avatar_url));
      }
    } catch { /* non-critical */ }

    void refreshPortfolioSubmission();

    // Expose window helpers for test automation — browser_type types into DOM but doesn't
    // fire SolidJS onInput handlers that update the reactive form signal. Direct signal
    // updates via __setField bypass this issue.
    // __setGender / __getGender are specialized helpers for the Gender select field,
    // which can fail with "Could not compute box model" when browser_click targets
    // <option> elements inside a <select> in some automation scenarios.
    if (typeof window !== "undefined") {
      (window as any).__setField = (key: string, val: string) => setField(key, val);
      (window as any).__setGender = (val: string) => setField("gender", val);
      (window as any).__getGender = () => form().gender ?? "";
    }
  });

  // Keep missingPortfolioLabels in sync with form changes for COMPANY role
  // For COMPANY: no server-side portfolio fields, documents not required for initial submission
  // missingDocLabels is a createMemo — auto-recomputes when form() changes, no manual reset needed
  createEffect(() => {
    if (props.roleKey !== "COMPANY") return;
    void form(); // track form changes
    setMissingPortfolioLabels([]);
  });

  const isLocked = () => ["PENDING", "UNDER_REVIEW"].includes(verificationStatus());

  const setField = (key: string, val: string) => setForm((prev) => ({ ...prev, [key]: val }));

  // Per-field validation notes — mirrors signup.tsx validation-note style
  const fieldNote = (
    key: string,
    label: string,
    required: boolean,
    fieldType?: string
  ) => {
    const value = String(form()[key] || "").trim();
    const filled = value.length > 0;

    // Determine validation function based on field key or type
    const isEmailField = key === "email" || key === "company_email";
    const isPhoneField = key === "phone" || key === "company_phone";
    const isNameField = key === "first_name" || key === "last_name" || key === "owner_name";
    const isURLField = fieldType === "url" || key === "website";

    // Validate based on field type
    let formatValid = true;
    if (filled) {
      if (isEmailField) {
        formatValid = isValidEmail(value);
      } else if (isPhoneField) {
        formatValid = isValidPhone(value);
      } else if (isNameField) {
        formatValid = isValidName(value);
      } else if (isURLField) {
        formatValid = isValidURL(value);
      }
    }

    if (!required) {
      // Optional field — only show note once something is typed
      if (!filled) return null;
      return (
        <p class="validation-note" style={{ color: "#fd6116" }}>
          ✓ {label} entered
        </p>
      );
    }

    // Required field — show validation state
    if (!filled) {
      return (
        <p class="validation-note" style={{ color: "#6e7591" }}>
          • {label} is required
        </p>
      );
    }

    if (!formatValid) {
      let hint = "";
      if (isEmailField) hint = "Enter a valid email format";
      else if (isPhoneField) hint = "Enter a valid 10-digit mobile number";
      else if (isNameField) hint = "Use only letters, spaces, hyphens, apostrophes";
      else if (isURLField) hint = "Enter a valid URL (e.g. https://example.com)";
      else hint = `Enter a valid ${label.toLowerCase()}`;
      return (
        <p class="validation-note" style={{ color: "#dc2626" }}>
          • {hint}
        </p>
      );
    }

    return (
      <p class="validation-note" style={{ color: "#fd6116" }}>
        ✓ {label} looks good
      </p>
    );
  };

  const handlePhotoUpload = async (file: File) => {
    setPhotoUploading(true);
    setPhotoMsg("");
    try {
      const token =
        typeof window !== "undefined"
          ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
          : "";
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch(`${API}/api/profile/photo`, {
        method: "POST",
        credentials: "include",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        body: fd,
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.avatar_url) {
        setAvatarUrl(data.avatar_url);
        setPhotoMsg("Photo updated.");
      } else {
        setPhotoMsg(data.error || "Upload failed.");
      }
    } catch {
      setPhotoMsg("Network error during upload.");
    } finally {
      setPhotoUploading(false);
      setTimeout(() => setPhotoMsg(""), 3000);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    setSaveMsg("");
    try {
      const { data, status } = await request("/api/profile", {
        method: "PATCH",
        body: { roleKey: props.roleKey, profile_data: { ...form(), ...docUrls() } },
      });
      if (status === 200) setSaveMsg("Saved successfully.");
      else setSaveMsg((data && (data.error || data.message)) || "Failed to save. Please try again.");
    } catch {
      setSaveMsg("Network error. Please try again.");
    } finally {
      setSaving(false);
      setTimeout(() => setSaveMsg(""), 3000);
    }
  };

  const handleSubmitForVerification = async () => {
    const portfolioMissing = await refreshPortfolioSubmission();
    if (missingBasicLabels().length > 0 || missingDocLabels().length > 0 || portfolioMissing.length > 0) {
      if (missingBasicLabels().length > 0) {
        setTab("basic");
        setSubmitMsg(`Complete required profile fields before submitting: ${missingBasicLabels().join(", ")}`);
      } else if (missingDocLabels().length > 0) {
        setTab("documents");
        setSubmitMsg(`Upload required documents before submitting: ${missingDocLabels().join(", ")}`);
      } else {
        setSubmitMsg(`Complete portfolio before submitting: ${portfolioMissing.join(", ")}. Go to My Portfolio.`);
      }
      return;
    }
    setSubmitting(true);
    setSubmitMsg("");
    try {
      const { status } = await request("/api/profile/submit-for-verification", {
        method: "POST",
        body: { roleKey: props.roleKey, profile_data: { ...form(), ...docUrls() } },
      });
      if (status === 200 || status === 201) {
        setVerificationStatus("PENDING");
        props.onVerificationStatusChange?.("PENDING");
        setSubmitMsg("Submitted! We will review your profile and notify you.");
      }
    } catch (err: any) {
      // request() throws on any non-2xx response with the backend's actual error
      // message (e.g. "A verification is already in progress...") — surface that
      // instead of a generic message, otherwise every failure looks identical and
      // unactionable regardless of cause.
      setSubmitMsg(err?.message || "Submission failed. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const statusColor: Record<string, string> = {
    PENDING: "#F59E0B",
    UNDER_REVIEW: "#3B82F6",
    DOCUMENTS_REQUESTED: "#FF5E13",
    REVISION_REQUESTED: "#FF5E13",
    APPROVED: "#10B981",
    REJECTED: "#EF4444",
    NOT_SUBMITTED: "#9CA3AF",
  };

  const statusLabel: Record<string, string> = {
    PENDING: "Pending Review",
    UNDER_REVIEW: "Under Review",
    DOCUMENTS_REQUESTED: "Documents Requested",
    REVISION_REQUESTED: "Revision Requested",
    APPROVED: "Approved",
    REJECTED: "Rejected",
    NOT_SUBMITTED: "Not Submitted",
  };

  const basicFields = createMemo(() =>
    applyRuntimeFields(getBasicFields(props.roleKey), resolveRuntimeFieldKeys(props.runtimeFields))
  );
  const requiredBasicFields = createMemo(() => basicFields().filter((field) => field.required));
  const requiredDocFields = createMemo(() => getDocFields(props.roleKey).filter((doc) => doc.required));
  const missingBasicLabels = createMemo(() =>
    requiredBasicFields()
      .filter((field) => !String(form()[field.key] || "").trim())
      .map((field) => field.label)
  );
  const missingDocLabels = createMemo(() =>
    requiredDocFields()
      .filter((doc) => !docUrls()[doc.key])
      .map((doc) => doc.label)
  );
  const canSubmitVerification = createMemo(
    () =>
      !isLocked() &&
      verificationStatus() !== "APPROVED" &&
      missingBasicLabels().length === 0 &&
      missingDocLabels().length === 0 &&
      missingPortfolioLabels().length === 0
  );

  // ── Wizard helpers (COMPANY only) ───────────────────────────────────────
  const wizardCanAdvance = createMemo(() => {
    if (wizardStep() === 0) return missingBasicLabels().length === 0;
    if (wizardStep() === 1) {
      return requiredDocFields().every((doc) => !!wizardDocs()[doc.key]);
    }
    return true;
  });

  const handleWizardSubmit = async () => {
    setWizardSubmitting(true);
    setWizardSubmitMsg("");
    try {
      const docs = Object.entries(wizardDocs()).map(([k, f]) => ({
        documentType: k,
        file: f,
      }));
      await submitCompanyProfileWithDocuments(
        { roleKey: props.roleKey, profile_data: form() },
        docs
      );
      setWizardSubmitSuccess(true);
      setVerificationStatus("PENDING");
      props.onVerificationStatusChange?.("PENDING");
    } catch (err: any) {
      setWizardSubmitMsg(err?.message ?? "Submission failed. Please try again.");
    } finally {
      setWizardSubmitting(false);
    }
  };

  return (
    <div style={{ "max-width": "760px" }}>
      <Show when={!(isCompany() && showWizard())} fallback={<CompanyWizard
        wizardStep={wizardStep}
        setWizardStep={setWizardStep}
        wizardDocs={wizardDocs}
        setWizardDocs={setWizardDocs}
        wizardDocErrors={wizardDocErrors}
        setWizardDocErrors={setWizardDocErrors}
        wizardSubmitting={wizardSubmitting}
        wizardSubmitMsg={wizardSubmitMsg}
        wizardSubmitSuccess={wizardSubmitSuccess}
        wizardCanAdvance={wizardCanAdvance}
        handleWizardSubmit={handleWizardSubmit}
        form={form}
        setField={setField}
        basicFields={basicFields}
        getDocFields={getDocFields}
        fieldNote={fieldNote}
        wizardReset={() => {
          setWizardStep(0);
          setWizardDocs({});
          setWizardDocErrors({});
          setWizardSubmitMsg("");
          setWizardSubmitSuccess(false);
        }}
      />}>
      <Show
        when={!showWizard()}
        fallback={
          <RoleWizard
            roleKey={props.roleKey}
            rolePrefix={rolePrefix()}
            onSubmitted={(status) => {
              setVerificationStatus(status);
              props.onVerificationStatusChange?.(status);
            }}
          />
        }
      >
      <Show when={submitMsg()}>
        <div
          style={{
            ...CARD,
            "margin-bottom": "16px",
            padding: "12px 16px",
            background: submitMsg().includes("Submitted") ? "#ECFDF5" : "#FEF2F2",
            border: `1px solid ${submitMsg().includes("Submitted") ? "#6EE7B7" : "#FECACA"}`,
            color: submitMsg().includes("Submitted") ? "#065F46" : "#B91C1C",
            "font-size": "13px",
            "font-weight": "600",
          }}
        >
          {submitMsg()}
        </div>
      </Show>

      {/* ── Tabs ──────────────────────────────────────────────────────── */}
      <div style={{ display: "flex", gap: "0px", "margin-bottom": "16px", "border-bottom": "1px solid #E5E7EB" }}>
        <For
          each={
            [
              { key: "basic", label: "Basic Information" },
              { key: "documents", label: "Documents" },
            ] as Array<{ key: Tab; label: string }>
          }
        >
          {(t) => (
            <button
              type="button"
              onClick={() => setTab(t.key)}
              style={{
                height: "44px",
                padding: "0 16px",
                "border-radius": "0px",
                border: "none",
                "border-bottom": tab() === t.key ? "2px solid #FF5E13" : "2px solid transparent",
                background: "transparent",
                color: tab() === t.key ? "#FF5E13" : "#6B7280",
                "font-size": "14px",
                "font-weight": tab() === t.key ? "700" : "500",
                cursor: "pointer",
                "margin-bottom": "-1px",
              }}
            >
              {t.label}
            </button>
          )}
        </For>
      </div>

      {/* ── Tab content ───────────────────────────────────────────────── */}
      <div style={CARD}>
        <Switch>
          {/* Basic Info */}
          <Match when={tab() === "basic"}>
            {/* Profile photo upload */}
            <div style={{ display: "flex", "align-items": "center", gap: "18px", "margin-bottom": "18px", "padding-bottom": "18px", "border-bottom": "1px solid #F3F4F6" }}>
              <div style={{ position: "relative", width: "72px", height: "72px", "flex-shrink": "0" }}>
                <Show
                  when={avatarUrl()}
                  fallback={
                    <div style={{ width: "72px", height: "72px", "border-radius": "50%", background: "#F3F4F6", display: "flex", "align-items": "center", "justify-content": "center", "font-size": "28px", color: "#9CA3AF", border: "2px solid #E5E7EB" }}>
                      👤
                    </div>
                  }
                >
                  <img
                    src={avatarUrl()}
                    alt="Profile photo"
                    style={{ width: "72px", height: "72px", "border-radius": "50%", "object-fit": "cover", border: "2px solid #E5E7EB" }}
                  />
                </Show>
              </div>
              <div>
                <p style={{ margin: "0 0 4px", "font-size": "13px", "font-weight": "700", color: "#111827" }}>Profile Photo</p>
                <p style={{ margin: "0 0 8px", "font-size": "12px", color: "#6B7280" }}>JPG, PNG or WebP · Max 5 MB</p>
                <label style={{ cursor: photoUploading() ? "not-allowed" : "pointer", display: "inline-block" }}>
                  <input
                    type="file"
                    accept="image/jpeg,image/png,image/webp,image/gif"
                    style={{ display: "none" }}
                    disabled={photoUploading()}
                    onChange={(e) => {
                      const file = e.currentTarget.files?.[0];
                      if (file) void handlePhotoUpload(file);
                      e.currentTarget.value = "";
                    }}
                  />
                  <span style={{ display: "inline-block", padding: "6px 14px", "border-radius": "6px", background: "#F9FAFB", border: "1px solid #D1D5DB", "font-size": "12px", "font-weight": "600", color: "#374151", opacity: photoUploading() ? "0.6" : "1" }}>
                    {photoUploading() ? "Uploading…" : "Change photo"}
                  </span>
                </label>
                <Show when={photoMsg()}>
                  <p style={{ margin: "4px 0 0", "font-size": "12px", color: photoMsg().includes("error") || photoMsg().includes("fail") ? "#B91C1C" : "#065F46", "font-weight": "600" }}>
                    {photoMsg()}
                  </p>
                </Show>
              </div>
            </div>
            <div style={{ display: "grid", "grid-template-columns": "1fr 1fr", gap: "10px" }}>
              <For each={basicFields()}>
                {(field) => (
                  <div style={{ "grid-column": field.type === "textarea" ? "span 2" : "span 1" }}>
                    <label style={LABEL}>
                      {field.label}
                      <Show when={field.required}>
                        <span style={{ color: "#EF4444" }}> *</span>
                      </Show>
                    </label>
                    <Switch>
                      <Match when={field.type === "textarea"}>
                        <textarea
                          rows={3}
                          disabled={fieldLocked(field.key)}
                          value={form()[field.key] ?? ""}
                          onInput={(e) => setField(field.key, e.currentTarget.value)}
                          style={{
                            ...INPUT,
                            height: "auto",
                            padding: "10px 12px",
                            resize: "vertical",
                            opacity: fieldLocked(field.key) ? "0.6" : "1",
                          }}
                        />
                      </Match>
                      <Match when={field.type === "select"}>
                        <select
                          disabled={fieldLocked(field.key)}
                          value={form()[field.key] ?? ""}
                          onChange={(e) => setField(field.key, e.currentTarget.value)}
                          style={{ ...INPUT, opacity: fieldLocked(field.key) ? "0.6" : "1" }}
                        >
                          <option value="">Select…</option>
                          <For each={field.options ?? []}>
                            {(opt) => <option value={opt}>{opt}</option>}
                          </For>
                        </select>
                      </Match>
                      <Match when={true}>
                        <input
                          type={field.type ?? "text"}
                          disabled={fieldLocked(field.key)}
                          value={form()[field.key] ?? ""}
                          onInput={(e) => setField(field.key, e.currentTarget.value)}
                          style={{ ...INPUT, opacity: fieldLocked(field.key) ? "0.6" : "1" }}
                        />
                      </Match>
                    </Switch>
                    {fieldNote(field.key, field.label, !!field.required, field.type)}
                    <Show when={verificationStatus() === "APPROVED" && lockedFieldIds().has(field.key)}>
                      <p style={{ margin: "4px 0 0", "font-size": "11px", color: "#9CA3AF" }}>
                        Locked after verification.
                      </p>
                    </Show>
                  </div>
                )}
              </For>
            </div>

            <Show when={isLocked()}>
              <p style={{ margin: "16px 0 0", "font-size": "12px", color: "#9CA3AF" }}>
                Profile is locked while verification is in progress.
              </p>
            </Show>
          </Match>

          {/* Documents */}
          <Match when={tab() === "documents"}>
            <div style={{ "margin-bottom": "20px" }}>
              <h3 style={{ margin: "0 0 4px", "font-size": "15px", color: "#111827" }}>
                Required Documents
              </h3>
              <p style={{ margin: "0", "font-size": "13px", color: "#6B7280" }}>
                Please upload clear, legible copies of the following documents. All documents must be valid and not expired.
              </p>
            </div>
            <div style={{ display: "flex", "flex-direction": "column", gap: "16px" }}>
              <For each={getDocFields(props.roleKey)}>
                {(doc) => (
                  <div
                    style={{
                      border: "1px dashed #E5E7EB",
                      "border-radius": "10px",
                      padding: "16px",
                    }}
                  >
                    <p
                      style={{
                        margin: "0",
                        "font-size": "13px",
                        "font-weight": "700",
                        color: "#111827",
                      }}
                    >
                      {doc.label}
                      <Show when={doc.required}>
                        <span style={{ color: "#EF4444" }}> *</span>
                      </Show>
                    </p>
                    <Show when={doc.hint}>
                      <p style={{ margin: "2px 0 10px", "font-size": "11px", color: "#9CA3AF" }}>
                        {doc.hint}
                      </p>
                    </Show>
                    <Show
                      when={docUrls()[doc.key]}
                      fallback={
                        <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                          <input
                            type="file"
                            id={`file-${doc.key}`}
                            style={{ display: "none" }}
                            disabled={fieldLocked(doc.key)}
                            onChange={async (e) => {
                              const file = e.currentTarget.files?.[0];
                              if (!file) return;
                              // Derive the role prefix for the API call
                              // JOB_SEEKER → jobseeker (singular, matches gateway route)
                              // Other roles → pluralize: PHOTOGRAPHER → photographers, COMPANY → companies
                              const rolePrefix = props.roleKey === 'JOB_SEEKER'
                                ? 'jobseeker'
                                : props.roleKey === 'COMPANY'
                                  ? 'companies'
                                  : props.roleKey === 'CATERING_SERVICES'
                                    ? 'catering-services'
                                    : props.roleKey.toLowerCase().replace(/_/g, '-') + 's';
                              try {
                                const result = await uploadDocument(rolePrefix, file, doc.key);
                                const url = result?.url ?? result?.file_url ?? result?.path ?? String(result);
                                setDocUrls(prev => ({ ...prev, [doc.key]: url }));
                                setDocUploadErrors(prev => ({ ...prev, [doc.key]: "" }));
                                await request("/api/profile", {
                                  method: "PATCH",
                                  body: { roleKey: props.roleKey, profile_data: { ...form(), ...docUrls(), [doc.key]: url } },
                                });
                              } catch (err: any) {
                                setDocUploadErrors(prev => ({ ...prev, [doc.key]: err.message ?? "Upload failed" }));
                              }
                            }}
                          />
                          <label
                            for={`file-${doc.key}`}
                            style={{
                              ...BTN_GHOST,
                              display: "inline-flex",
                              "align-items": "center",
                              "line-height": "1",
                              opacity: fieldLocked(doc.key) ? "0.5" : "1",
                              cursor: fieldLocked(doc.key) ? "not-allowed" : "pointer",
                            }}
                          >
                            Choose File
                          </label>
                          <span style={{ "font-size": "12px", color: "#9CA3AF" }}>
                            No file chosen
                          </span>
                        </div>
                      }
                    >
                      <div style={{ display: "flex", "align-items": "center", gap: "10px" }}>
                        <span
                          style={{
                            "font-size": "12px",
                            "font-weight": "600",
                            color: "#10B981",
                            background: "#ECFDF5",
                            padding: "4px 10px",
                            "border-radius": "6px",
                          }}
                        >
                          ✓ Uploaded
                        </span>
                        <Show when={!fieldLocked(doc.key)}>
                          <button
                            type="button"
                            onClick={() => {
                              setDocUrls(prev => {
                                const next = { ...prev };
                                delete next[doc.key];
                                return next;
                              });
                            }}
                            style={{
                              ...BTN_GHOST,
                              height: "28px",
                              "font-size": "11px",
                              padding: "0 10px",
                            }}
                          >
                            Remove
                          </button>
                        </Show>
                      </div>
                    </Show>
                    <Show when={docUploadErrors()[doc.key]}>
                      <p style={{ margin: "4px 0 0", "font-size": "11px", color: "#EF4444" }}>
                        {docUploadErrors()[doc.key]}
                      </p>
                    </Show>
                  </div>
                )}
              </For>
            </div>
          </Match>
        </Switch>
      </div>

      {/* ── Save button ─────────────────────────────────────────────── */}
      <div style={{ display: "flex", "align-items": "center", gap: "12px", "margin-top": "16px" }}>
        <button
          type="button"
          onClick={handleSave}
          disabled={saving() || isLocked() || missingBasicLabels().length > 0}
          style={{ ...BTN_PRIMARY, opacity: saving() || isLocked() || missingBasicLabels().length > 0 ? "0.6" : "1" }}
        >
          {saving() ? "Saving…" : "Save Changes"}
        </button>
        <Show when={saveMsg()}>
          <span
            style={{
              "font-size": "13px",
              "font-weight": "600",
              color: saveMsg().includes("success") ? "#10B981" : "#EF4444",
            }}
          >
            {saveMsg()}
          </span>
        </Show>
      </div>

      {/* ── Submit for Verification button ───────────────────────────── */}
      <Show when={true}>
        <div
          style={{
            display: "flex",
            "flex-direction": "column",
            gap: "6px",
            "margin-top": "16px",
            padding: "16px",
            background: "#FAFAFA",
            "border-radius": "10px",
            border: "1px solid #E5E7EB",
          }}
        >
          <div style={{ display: "flex", "align-items": "center", gap: "12px" }}>
            <button
              type="button"
              onClick={handleSubmitForVerification}
              disabled={!canSubmitVerification() || submitting()}
              style={{
                ...BTN_PRIMARY,
                opacity: !canSubmitVerification() || submitting() ? "0.5" : "1",
                cursor: !canSubmitVerification() ? "not-allowed" : "pointer",
              }}
            >
              {submitting() ? "Submitting…" : "Submit for Verification"}
            </button>
            <Show when={!canSubmitVerification() && !submitting()}>
              <span style={{ "font-size": "12px", color: "#9CA3AF" }}>
                {(() => {
                  const parts: string[] = [];
                  if (missingBasicLabels().length) parts.push(missingBasicLabels().join(", "));
                  if (missingDocLabels().length) parts.push(missingDocLabels().join(", "));
                  if (missingPortfolioLabels().length) parts.push(`${missingPortfolioLabels().join(", ")} (in My Portfolio)`);
                  return parts.length ? `Missing: ${parts.join("; ")}` : "Complete all required fields to submit";
                })()}
              </span>
            </Show>
          </div>
          <Show when={!isLocked() && verificationStatus() === "NOT_SUBMITTED" && missingPortfolioLabels().length === 0 && missingBasicLabels().length === 0 && missingDocLabels().length === 0}>
            <p style={{ margin: "0", "font-size": "12px", color: "#6B7280" }}>
              Submitting locks your profile for review. You will be notified once the admin reviews it.
            </p>
          </Show>
        </div>
      </Show>
      </Show>
      </Show>
    </div>
  );
}
