// Lotus Assist — FormRenderer
// Takes a schema, renders a branded form, handles state + validation + submit.
// The whole point: to add a new form, you write a schema, not a component.

const { useState: useFormState } = React;

function FormRenderer({ schema, onSubmit }) {
  const [values, setValues] = useFormState(schema.defaults || {});
  const [errors, setErrors] = useFormState({});
  const [submitting, setSubmitting] = useFormState(false);
  const [submitted, setSubmitted] = useFormState(false);

  const setValue = (name) => (v) => {
    setValues((prev) => ({ ...prev, [name]: v }));
    if (errors[name]) setErrors((prev) => ({ ...prev, [name]: null }));
  };

  // Conditional visibility. Supported operators:
  //   equals      — current === value
  //   notEquals   — current !== value
  //   includes    — array value contains item (for checkbox groups)
  //   inSet       — current is one of [a, b, …]
  const isVisible = (field) => {
    if (!field.showIf) return true;
    const { field: refField, equals, notEquals, includes, inSet } = field.showIf;
    const current = values[refField];
    if (equals !== undefined) return current === equals;
    if (notEquals !== undefined) return current !== notEquals;
    if (includes !== undefined) return Array.isArray(current) && current.includes(includes);
    if (inSet !== undefined) return Array.isArray(inSet) && inSet.includes(current);
    return true;
  };

  const visibleFields = (schema.fields || []).filter(isVisible);

  const validate = () => {
    const errs = {};
    visibleFields.forEach((f) => {
      if (f.type === "heading") return;
      const v = values[f.name];
      if (f.required && (v === undefined || v === "" || v === null || (Array.isArray(v) && v.length === 0))) {
        errs[f.name] = "This field is required.";
      }
      if (f.type === "email" && v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) {
        errs[f.name] = "Please enter a valid email address.";
      }
    });
    return errs;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) {
      setErrors(errs);
      // Scroll to first error
      setTimeout(() => {
        const first = document.querySelector("[data-field-error='true']");
        first?.scrollIntoView({ behavior: "smooth", block: "center" });
      }, 50);
      return;
    }
    setSubmitting(true);
    try {
      await onSubmit?.(values);
      setSubmitted(true);
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return <SubmitSuccess schema={schema} values={values} onReset={() => { setSubmitted(false); setValues(schema.defaults || {}); }} />;
  }

  return (
    <form onSubmit={handleSubmit} noValidate style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {visibleFields.map((field, i) => (
        <div key={field.name || `heading-${i}`} data-field-error={errors[field.name] ? "true" : "false"}>
          <Field
            field={field}
            value={values[field.name]}
            onChange={setValue(field.name)}
            error={errors[field.name]}
          />
        </div>
      ))}

      <div style={{ display: "flex", justifyContent: "flex-start", marginTop: 8 }}>
        <button
          type="submit"
          disabled={submitting}
          style={{
            padding: "16px 36px",
            background: "var(--brand)",
            color: "#fff",
            border: 0,
            borderRadius: 999,
            fontSize: 16,
            fontWeight: 600,
            fontFamily: "inherit",
            cursor: submitting ? "wait" : "pointer",
            opacity: submitting ? 0.7 : 1,
            boxShadow: "0 4px 12px rgba(0,109,121,.22)",
            transition: "all 180ms var(--ease-out)",
          }}
          onMouseOver={(e) => { if (!submitting) e.currentTarget.style.background = "var(--brand-hover)"; }}
          onMouseOut={(e) => { e.currentTarget.style.background = "var(--brand)"; }}
        >
          {submitting ? "Submitting…" : (schema.submitLabel || "Submit")}
        </button>
      </div>
    </form>
  );
}

function SubmitSuccess({ schema, values, onReset }) {
  const name = values.participant_name || values.name_completing || values.name || "";
  const firstName = name.split(" ")[0];
  return (
    <div style={{ textAlign: "center", padding: "32px 16px" }}>
      <div style={{
        width: 88, height: 88, borderRadius: 999,
        background: "var(--la-green-100)", color: "var(--la-green-700)",
        fontSize: 44, display: "flex", alignItems: "center", justifyContent: "center",
        margin: "0 auto 20px",
      }}>
        <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
      </div>
      <h2 style={{ margin: "0 0 10px", color: "var(--la-teal-900)", fontSize: 28 }}>
        Thanks{firstName ? `, ${firstName}` : ""} — we've got it.
      </h2>
      <p style={{ color: "var(--fg-soft)", fontSize: 16, margin: "0 auto 24px", maxWidth: 480, lineHeight: 1.6 }}>
        {schema.successMessage || "Your response has been sent to the Lotus Assist team. We'll be in touch within one business day if any follow-up is needed."}
      </p>
      <button
        type="button"
        onClick={onReset}
        style={{
          padding: "10px 22px",
          background: "transparent",
          color: "var(--brand)",
          border: "2px solid var(--brand)",
          borderRadius: 999, fontSize: 14, fontWeight: 600,
          cursor: "pointer", fontFamily: "inherit",
        }}
      >Submit another response</button>
    </div>
  );
}

Object.assign(window, { FormRenderer, SubmitSuccess });
