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

function UrgencyWidget() { return null; }

const t = window.t;

const DIAL_CODES = [
  { cc: "us",  code: "+1",   name: "USA"          },
  { cc: "gb",  code: "+44",  name: "UK"           },
  { cc: "nl",  code: "+31",  name: "Netherlands"  },
  { cc: "de",  code: "+49",  name: "Germany"      },
  { cc: "fr",  code: "+33",  name: "France"       },
  { cc: "es",  code: "+34",  name: "Spain"        },
  { cc: "it",  code: "+39",  name: "Italy"        },
  { cc: "pl",  code: "+48",  name: "Poland"       },
  { cc: "cz",  code: "+420", name: "Czech Rep."   },
  { cc: "sk",  code: "+421", name: "Slovakia"     },
  { cc: "si",  code: "+386", name: "Slovenia"     },
  { cc: "ru",  code: "+7",   name: "Russia"       },
  { cc: "be",  code: "+32",  name: "Belgium"      },
  { cc: "at",  code: "+43",  name: "Austria"      },
  { cc: "au",  code: "+61",  name: "Australia"    },
  { cc: "nz",  code: "+64",  name: "New Zealand"  },
  { cc: "hr",  code: "+385", name: "Croatia"      },
];

const LANG_DIAL = {
  en: "us", fr: "fr", es: "es", de: "de", it: "it",
  pl: "pl", nl: "nl", cs: "cz", sk: "sk", sl: "si", ru: "ru",
};

function dialIdxForLang(lang) {
  const cc  = LANG_DIAL[lang] || "us";
  const idx = DIAL_CODES.findIndex(d => d.cc === cc);
  return idx >= 0 ? idx : 0;
}

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: "", surname: "", email: "", phone: "", backup_phone: "", country: "", agreed: false });
  const [dialIdx, setDialIdx]   = React.useState(() => dialIdxForLang(window.LANG || 'en'));
  const [dialOpen, setDialOpen] = React.useState(false);
  const [errors, setErrors]     = React.useState({});
  const [loading, setLoading]   = React.useState(false);
  const [apiError, setApiError] = React.useState("");

  React.useEffect(() => {
    const handler = e => setDialIdx(dialIdxForLang(e.detail || window.LANG || 'en'));
    window.addEventListener('langchange', handler);
    return () => window.removeEventListener('langchange', handler);
  }, []);

  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 = t("form.err_name");
    if (form.surname.trim().length < 2) errs.surname = t("form.err_surname");
    if (!form.email.includes("@") || !form.email.includes(".")) errs.email = t("form.err_email");
    if (form.phone.replace(/\D/g, "").length < 6) errs.phone = t("form.err_phone");
    if (!form.agreed) errs.agreed = t("form.err_agreed");
    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(),
        surname:      form.surname.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",
        subid:         localStorage.getItem("green_subid")         || "",
        campaign_name: localStorage.getItem("green_campaign_name") || "",
        adset_name:    localStorage.getItem("green_adset_name")    || "",
        ad_name:       localStorage.getItem("green_ad_name")       || "",
      };
      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) {
        window.location.href = (json.autologin && json.autologin.length > 5)
          ? json.autologin
          : "thank-you.html";
      } else if (json.errors) {
        setErrors(json.errors);
      } else {
        setApiError(json.error || t("form.err_generic"));
      }
    } catch {
      setApiError(t("form.err_conn"));
    } 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={t("form.name")}
          type="text" disabled={loading} style={baseField(errors.name)} />
        {errors.name && <div style={errSt}>{errors.name}</div>}
      </div>

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

      {/* Email */}
      <div style={{ marginBottom: 10 }}>
        <input value={form.email} onChange={set("email")} placeholder={t("form.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={t("form.phone")} 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={t("form.backup")} 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 }}>
          {t("form.backup_hint")}
        </div>
      </div>

      {/* Country */}
      <div style={{ marginBottom: 12, marginTop: 10 }}>
        <input value={form.country} onChange={set("country")}
          placeholder={t("form.country")}
          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" }}>
          {t("form.agree")}{" "}
          <a href="privacy-policy.html" style={{ color: dark ? "rgba(255,255,255,0.75)" : "#005254", textDecoration: "underline" }}>{t("form.agree_link")}</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 ? t("form.sending") : t("form.submit")}
      </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,
};
