// RegistrationForm.jsx
Object.assign(window, { ContactForm, UrgencyWidget, RegistrationForm });

function UrgencyWidget() { return null; }

const DIAL_CODES = [
  { cc: "nl", code: "+31",  name: "Netherlands" },
  { cc: "de", code: "+49",  name: "Germany"     },
  { cc: "it", code: "+39",  name: "Italy"       },
  { cc: "fr", code: "+33",  name: "France"      },
  { cc: "pl", code: "+48",  name: "Poland"      },
  { cc: "es", code: "+34",  name: "Spain"       },
  { cc: "gb", code: "+44",  name: "UK"          },
  { cc: "be", code: "+32",  name: "Belgium"     },
  { cc: "at", code: "+43",  name: "Austria"     },
  { cc: "cz", code: "+420", name: "Czech Rep."  },
  { cc: "us", code: "+1",   name: "USA"         },
];

const FlagImg = ({ cc }) => (
  <img
    src={`https://flagcdn.com/w20/${cc}.png`}
    srcSet={`https://flagcdn.com/w40/${cc}.png 2x`}
    width="20" height="14"
    alt={cc}
    style={{ borderRadius: 2, objectFit: "cover", flexShrink: 0 }}
  />
);

function ContactForm({ dark }) {
  const [form, setForm]         = React.useState({ name: "", email: "", phone: "", backup_phone: "", country: "", agreed: false });
  const [dialIdx, setDialIdx]   = React.useState(0);
  const [dialOpen, setDialOpen] = React.useState(false);
  const [errors, setErrors]     = React.useState({});
  const [loading, setLoading]   = React.useState(false);
  const [apiError, setApiError] = React.useState("");

  const set = k => e => {
    const v = e.target.type === "checkbox" ? e.target.checked : e.target.value;
    setForm(f => ({ ...f, [k]: v }));
    setErrors(p => ({ ...p, [k]: "" }));
    setApiError("");
  };

  const validate = () => {
    const errs = {};
    if (form.name.trim().length < 2) errs.name = "Please enter your name";
    if (!form.email.includes("@") || !form.email.includes(".")) errs.email = "Invalid email address";
    if (form.phone.replace(/\D/g, "").length < 6) errs.phone = "Invalid phone number";
    if (!form.agreed) errs.agreed = "Please agree to the Privacy Policy";
    return errs;
  };

  const handleSubmit = async () => {
    const clientErrors = validate();
    if (Object.keys(clientErrors).length > 0) { setErrors(clientErrors); return; }
    setLoading(true);
    setApiError("");
    if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
      window.location.href = "thank-you.html";
      return;
    }
    try {
      const dc = DIAL_CODES[dialIdx];
      const payload = {
        name:         form.name.trim(),
        email:        form.email.trim(),
        phone:        dc.code + form.phone.replace(/\D/g, ""),
        backup_phone: form.backup_phone.trim(),
        country:      form.country.trim(),
        website:      "",
        form_id:      "reg_form_v1",
      };
      const res  = await fetch("api/send.php", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify(payload),
      });
      const json = await res.json();
      if (json.ok) {
        const dest = "thank-you.html" + (json.redirect ? "?to=" + encodeURIComponent(json.redirect) : "");
        window.location.href = dest;
      } else if (json.errors) {
        setErrors(json.errors);
      } else {
        setApiError(json.error || "Error processing. Please try again.");
      }
    } catch {
      setApiError("Connection error. Please check your internet and try again.");
    } finally {
      setLoading(false);
    }
  };

  const BG  = dark ? "rgba(255,255,255,0.1)"        : "#fff";
  const CLR = dark ? "#fff"                          : "#1a2c38";
  const BRD = hasErr => hasErr
    ? "1.5px solid #f4874b"
    : `1px solid ${dark ? "rgba(255,255,255,0.18)" : "#dde2e8"}`;

  const baseField = hasErr => ({
    width: "100%", height: 52,
    background: BG,
    border: BRD(hasErr),
    borderRadius: 8,
    padding: "0 16px",
    fontFamily: "Inter, Arial, sans-serif",
    fontSize: 15, color: CLR,
    outline: "none",
    boxSizing: "border-box",
    display: "block",
    opacity: loading ? 0.7 : 1,
  });

  const dc = DIAL_CODES[dialIdx];

  return (
    <div id="registration" onClick={() => dialOpen && setDialOpen(false)}>
      <input type="text" name="website" style={{ display: "none" }} tabIndex={-1} autoComplete="off" />

      {/* Name */}
      <div style={{ marginBottom: 10 }}>
        <input value={form.name} onChange={set("name")} placeholder="Your name"
          type="text" disabled={loading} style={baseField(errors.name)} />
        {errors.name && <div style={errSt}>{errors.name}</div>}
      </div>

      {/* Email */}
      <div style={{ marginBottom: 10 }}>
        <input value={form.email} onChange={set("email")} placeholder="Your email"
          type="email" disabled={loading} style={baseField(errors.email)} />
        {errors.email && <div style={errSt}>{errors.email}</div>}
      </div>

      {/* Phone with dial code */}
      <div style={{ marginBottom: 10, position: "relative" }}>
        <div style={{
          display: "flex", alignItems: "center",
          height: 52, background: BG,
          border: BRD(errors.phone),
          borderRadius: 8,
          opacity: loading ? 0.7 : 1,
        }}>
          <div onClick={e => { e.stopPropagation(); setDialOpen(v => !v); }} style={{
            display: "flex", alignItems: "center", gap: 5,
            padding: "0 12px",
            borderRight: `1px solid ${dark ? "rgba(255,255,255,0.18)" : "#dde2e8"}`,
            cursor: "pointer", height: "100%", flexShrink: 0, userSelect: "none",
          }}>
            <FlagImg cc={dc.cc} />
            <svg width="10" height="6" viewBox="0 0 10 6" fill="none">
              <path d="M1 1L5 5L9 1" stroke={dark ? "rgba(255,255,255,0.55)" : "#888"} strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
            <span style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 14, color: CLR, fontWeight: 600 }}>{dc.code}</span>
          </div>
          <input value={form.phone} onChange={set("phone")}
            placeholder="(000) 000-0000" type="tel" disabled={loading}
            style={{ flex: 1, background: "transparent", border: "none", padding: "0 14px", fontFamily: "Inter, Arial, sans-serif", fontSize: 15, color: CLR, outline: "none" }}
          />
        </div>
        {dialOpen && (
          <div onClick={e => e.stopPropagation()} className="dial-dropdown" style={{
            position: "absolute", top: "calc(100% + 6px)", left: 0,
            background: "#003E40",
            borderRadius: 10,
            boxShadow: "0 12px 32px rgba(0,0,0,0.35)",
            zIndex: 999, minWidth: 240, maxHeight: 300, overflowY: "auto",
            border: "1px solid rgba(255,255,255,0.12)",
          }}>
            {DIAL_CODES.map((d, i) => (
              <div key={i} onClick={() => { setDialIdx(i); setDialOpen(false); }}
                style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "11px 16px", cursor: "pointer",
                  background: i === dialIdx ? "rgba(255,255,255,0.12)" : "transparent",
                  borderBottom: i < DIAL_CODES.length - 1 ? "1px solid rgba(255,255,255,0.07)" : "none",
                  transition: "background 0.12s",
                }}>
                <FlagImg cc={d.cc} />
                <span style={{ fontFamily: "Unbounded, sans-serif", fontSize: 13, fontWeight: 400, color: "#fff", flex: 1 }}>{d.name}</span>
                <span style={{ fontFamily: "Unbounded, sans-serif", fontSize: 12, fontWeight: 500, color: "#f4874b" }}>{d.code}</span>
              </div>
            ))}
          </div>
        )}
        {errors.phone && <div style={errSt}>{errors.phone}</div>}
      </div>

      {/* Backup phone */}
      <div style={{ marginBottom: 4 }}>
        <input value={form.backup_phone} onChange={set("backup_phone")}
          placeholder="Backup contact number" type="tel" disabled={loading}
          style={baseField(false)} />
        <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 11, color: dark ? "rgba(255,255,255,0.4)" : "#aab0b8", marginTop: 4, paddingLeft: 2, lineHeight: 1.4 }}>
          *This may help us contact you if the primary number was entered incorrectly
        </div>
      </div>

      {/* Country */}
      <div style={{ marginBottom: 12, marginTop: 10 }}>
        <input value={form.country} onChange={set("country")}
          placeholder="Your country (for example, Portugal)*"
          type="text" disabled={loading} style={baseField(false)} />
      </div>

      {/* Checkbox */}
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: errors.agreed ? 4 : 14 }}>
        <input type="checkbox" checked={form.agreed} onChange={set("agreed")}
          id="agree-cb" disabled={loading}
          style={{ marginTop: 3, flexShrink: 0, width: 16, height: 16, accentColor: "#f4874b", cursor: "pointer" }} />
        <label htmlFor="agree-cb" style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 12, color: dark ? "rgba(255,255,255,0.55)" : "#888", lineHeight: 1.5, cursor: "pointer" }}>
          By clicking the "Free Consultation" button, you agree to the{" "}
          <a href="#" style={{ color: dark ? "rgba(255,255,255,0.75)" : "#005254", textDecoration: "underline" }}>Privacy Policy</a>
        </label>
      </div>
      {errors.agreed && <div style={{ ...errSt, marginBottom: 10 }}>{errors.agreed}</div>}

      {apiError && (
        <div style={{ fontFamily: "Inter, Arial, sans-serif", fontSize: 13, color: "#f4874b", textAlign: "center", marginBottom: 10, lineHeight: 1.4 }}>{apiError}</div>
      )}

      <button onClick={handleSubmit} disabled={loading} style={{
        width: "100%", height: 54,
        background: loading ? "#d4692e" : "#f4874b",
        border: "none", borderRadius: 10,
        color: "#fff",
        fontFamily: "Montserrat, Arial, sans-serif", fontWeight: 700, fontSize: 14,
        cursor: loading ? "not-allowed" : "pointer",
        textTransform: "uppercase", letterSpacing: 1,
        transition: "background 0.15s",
      }}>
        {loading ? "SENDING..." : "GET FREE CONSULTATION"}
      </button>
    </div>
  );
}

function RegistrationForm(props) { return <ContactForm {...props} dark={false} />; }

const errSt = {
  fontFamily: "Inter, Arial, sans-serif",
  fontSize: 11, color: "#f4874b",
  marginTop: 4, paddingLeft: 2,
};
