// RegistrationForm.jsx

/* ── Countdown — 12h from session start, persists in sessionStorage ── */
function UrgencyWidget() {
  const getInitialSeconds = () => {
    const key = "reg_deadline_euro";
    const stored = sessionStorage.getItem(key);
    if (stored) {
      const remaining = Math.floor((parseInt(stored) - Date.now()) / 1000);
      if (remaining > 0) return remaining;
    }
    const deadline = Date.now() + 12 * 3600 * 1000;
    sessionStorage.setItem(key, deadline.toString());
    return 12 * 3600;
  };

  const [seconds, setSeconds] = React.useState(getInitialSeconds);

  React.useEffect(() => {
    const t = setInterval(() => setSeconds(s => s > 0 ? s - 1 : 0), 1000);
    return () => clearInterval(t);
  }, []);

  const pad = n => String(n).padStart(2, "0");
  const days  = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins  = Math.floor((seconds % 3600) / 60);
  const secs  = seconds % 60;

  const Block = ({ val, label }) => (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 5 }}>
      <div className="timer-block-inner" style={{
        background: "#fff", border: "1px solid #ddd", borderRadius: 6,
        padding: "8px 14px", minWidth: 54, textAlign: "center",
        fontFamily: "'Courier New', 'Roboto Mono', monospace",
        fontWeight: 700, fontSize: 26, color: "#111", lineHeight: 1,
        boxShadow: "0 1px 4px rgba(0,0,0,0.07)",
      }}>
        {val}
      </div>
      <span className="timer-label" style={{
        fontFamily: "Arial, sans-serif", fontSize: 9, color: "#888",
        textTransform: "uppercase", letterSpacing: 0.8,
      }}>
        {label}
      </span>
    </div>
  );

  return (
    <div style={{ textAlign: "center", marginBottom: 20, padding: "20px 0 4px" }}>
      <p style={{ fontFamily: "'Times New Roman', serif", fontSize: 15, color: "#333", marginBottom: 16, lineHeight: 1.5 }}>
        Pažnja! Registracija se zatvara za:
      </p>
      <div style={{ display: "flex", justifyContent: "center", alignItems: "flex-start", gap: 6 }}>
        <Block val={pad(days)}  label="DANI" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 26, color: "#555", paddingTop: 8, lineHeight: 1 }}>:</span>
        <Block val={pad(hours)} label="SATI" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 26, color: "#555", paddingTop: 8, lineHeight: 1 }}>:</span>
        <Block val={pad(mins)}  label="MINUTE" />
        <span className="timer-sep" style={{ fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 26, color: "#555", paddingTop: 8, lineHeight: 1 }}>:</span>
        <Block val={pad(secs)}  label="SEKUNDE" />
      </div>
    </div>
  );
}

/* ── Registration form ── */
function RegistrationForm() {
  const FORM_ID = "reg_form_eurofunding_v1";

  const [form, setForm]     = React.useState({ nombre: "", apellido: "", email: "", telefono: "" });
  const [touched, setTouched] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const [apiError, setApiError] = React.useState("");

  /* ── Validation rules (match new stack form-scripts.js) ── */
  const validators = {
    nombre:   v => v.trim().length >= 2 && !/\d/.test(v.trim()),
    apellido: v => v.trim().length >= 2 && !/\d/.test(v.trim()),
    email:    v => /^\S+@\S+\.[A-Za-z]{2,}$/.test(v.trim()),
    telefono: v => v.replace(/\D/g, "").length === 9,
  };

  const errMsgs = {
    nombre:   "Vaše ime je prekratko (najmanje 2 slova, bez brojeva)",
    apellido: "Vaše prezime je prekratko (najmanje 2 slova, bez brojeva)",
    email:    "Unesite ispravnu email adresu",
    telefono: "Unesite valjani broj mobitela (9 znamenki)",
  };

  const isValid  = k => validators[k](form[k]);
  const allValid = Object.keys(validators).every(isValid);
  const showErr  = k => touched[k] && !isValid(k);

  /* ── Handlers ── */
  const onChange = (k, filter) => e => {
    let v = e.target.value;
    if (filter) v = v.replace(filter, "");
    setForm(f => ({ ...f, [k]: v }));
    setApiError("");
  };

  const onBlur = k => () => setTouched(t => ({ ...t, [k]: true }));

  /* ── Cookie helpers (duplicate-email guard) ── */
  const getCookie = name => {
    const m = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
    return m ? decodeURIComponent(m[2]) : null;
  };
  const setCookie = (name, value, sec) => {
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${new Date(Date.now() + sec * 1000).toUTCString()}; path=/`;
  };

  /* ── Submit ── */
  const handleSubmit = async () => {
    // Touch all to reveal any hidden errors
    setTouched({ nombre: true, apellido: true, email: true, telefono: true });
    if (!allValid) return;

    // Duplicate email guard
    const emailTrimmed = form.email.trim();
    if (getCookie("user_email_recent") === emailTrimmed) {
      setApiError("Već ste ostavili zahtjev. Molimo pričekajte poziv savjetnika.");
      return;
    }

    setLoading(true);
    setApiError("");

    if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
      window.location.href = "thank-you.html";
      return;
    }

    try {
      const tracking = {};
      ["subid", "campaign_name", "adset_name", "ad_name"].forEach(k => {
        const v = localStorage.getItem("euro_" + k);
        if (v) tracking[k] = v;
      });

      const res = await fetch("api/send.php", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nombre:   form.nombre.trim(),
          apellido: form.apellido.trim(),
          email:    emailTrimmed,
          telefono: form.telefono.replace(/\D/g, ""),
          website:  "",
          form_id:  FORM_ID,
          ...tracking,
        }),
      });

      const json = await res.json();
      if (json.ok) {
        setCookie("user_email_recent", emailTrimmed, 3600);
        window.location.href = json.url || "thank-you.html";
      } else if (json.errors) {
        const t = {};
        Object.keys(json.errors).forEach(k => { t[k] = true; });
        setTouched(t);
        setApiError(Object.values(json.errors)[0] || "");
      } else {
        setApiError(json.error || "Greška pri obradi. Pokušajte ponovo.");
      }
    } catch {
      setApiError("Greška veze. Provjerite internet i pokušajte ponovo.");
    } finally {
      setLoading(false);
    }
  };

  /* ── Input border state ── */
  const borderStyle = k => {
    if (!touched[k]) return "1.5px solid #ccc";
    return isValid(k) ? "2px solid #28a745" : "2px solid #e53935";
  };

  const baseInp = k => ({
    width: "100%", height: 52, background: "#fff", borderRadius: 26,
    border: borderStyle(k), padding: "0 20px",
    fontFamily: "Arial, sans-serif", fontSize: 15, color: "#202020",
    outline: "none", boxSizing: "border-box", opacity: loading ? 0.7 : 1,
  });

  const ErrorMsg = ({ k }) => showErr(k) ? (
    <div style={{
      fontFamily: "Arial, sans-serif", fontSize: 11, color: "#fff",
      background: "#eb162b", padding: "5px 10px", borderRadius: 4, marginTop: 4,
    }}>
      {errMsgs[k]}
    </div>
  ) : null;

  return (
    <div>
      {/* Honeypot */}
      <input type="text" name="website" style={{ display: "none" }} tabIndex={-1} autoComplete="off" readOnly />

      {/* Ime */}
      <div style={{ marginBottom: 10 }}>
        <input
          value={form.nombre} onChange={onChange("nombre", /[^a-zA-ZÀ-žА-яЁё\s'-]/g)}
          onBlur={onBlur("nombre")} placeholder="Vaše ime"
          disabled={loading} style={baseInp("nombre")}
        />
        <ErrorMsg k="nombre" />
      </div>

      {/* Prezime */}
      <div style={{ marginBottom: 10 }}>
        <input
          value={form.apellido} onChange={onChange("apellido", /[^a-zA-ZÀ-žА-яЁё\s'-]/g)}
          onBlur={onBlur("apellido")} placeholder="Tvoje prezime"
          disabled={loading} style={baseInp("apellido")}
        />
        <ErrorMsg k="apellido" />
      </div>

      {/* Email */}
      <div style={{ marginBottom: 10 }}>
        <input
          value={form.email} onChange={onChange("email")}
          onBlur={onBlur("email")} placeholder="Tvoj email"
          type="email" disabled={loading} style={baseInp("email")}
        />
        <ErrorMsg k="email" />
      </div>

      {/* Telefon +385 */}
      <div style={{ marginBottom: 16 }}>
        <div style={{
          width: "100%", height: 52, background: "#fff", borderRadius: 26,
          border: borderStyle("telefono"),
          display: "flex", alignItems: "center", overflow: "hidden",
          opacity: loading ? 0.7 : 1,
        }}>
          <div style={{
            height: 52, padding: "0 14px", borderRight: "1px solid #e0e0e0",
            display: "flex", alignItems: "center", gap: 6, flexShrink: 0,
          }}>
            <svg width="22" height="15" viewBox="0 0 22 15" style={{ display: "block", borderRadius: 2 }}>
              <rect width="22" height="5" fill="#FF0000"/>
              <rect y="5" width="22" height="5" fill="#FFFFFF"/>
              <rect y="10" width="22" height="5" fill="#003399"/>
            </svg>
            <span style={{ fontFamily: "Arial, sans-serif", fontSize: 14, color: "#111", fontWeight: 600 }}>+385</span>
          </div>
          <input
            value={form.telefono}
            onChange={onChange("telefono", /[^\d]/g)}
            onBlur={onBlur("telefono")}
            placeholder="Vaš mobilni telefon"
            type="tel" disabled={loading}
            style={{ flex: 1, background: "transparent", border: "none", padding: "0 14px", fontFamily: "Arial, sans-serif", fontSize: 15, color: "#202020", outline: "none" }}
          />
        </div>
        <ErrorMsg k="telefono" />
      </div>

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

      <button
        onClick={handleSubmit}
        disabled={loading}
        style={{
          width: "100%", height: 52,
          background: loading ? "#888" : "#5cb85c",
          border: "none", borderRadius: 26, color: "#fff",
          fontFamily: "Arial, sans-serif", fontWeight: 700, fontSize: 16,
          cursor: loading ? "not-allowed" : "pointer",
          opacity: (!allValid && !loading) ? 0.65 : 1,
          transition: "background 0.15s, opacity 0.15s",
        }}
      >
        {loading ? "Slanje..." : "Registracija"}
      </button>
    </div>
  );
}

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