/* global React */

const INPUT_BASE = {
  fontFamily: "var(--font-body)", fontSize: 15, padding: "10px 12px",
  background: "var(--paper)", borderRadius: 2, color: "var(--ink)",
  width: "100%", boxSizing: "border-box", outline: "none",
  transition: "border-color 150ms", appearance: "auto"
};

const SmartInput = ({ as: Tag = "input", error, style: extra = {}, onFocus, onBlur, children, ...rest }) => {
  const [focused, setFocused] = React.useState(false);
  const border = error ? "1px solid #c0392b" : focused ? "1px solid var(--teal)" : "1px solid var(--hairline)";
  return (
    <Tag
      {...rest}
      onFocus={e => { setFocused(true); if (onFocus) onFocus(e); }}
      onBlur={e => { setFocused(false); if (onBlur) onBlur(e); }}
      style={{ ...INPUT_BASE, border, ...extra }}
    >
      {children}
    </Tag>
  );
};

const Field = ({ label, required, error, hint, children }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 16 }}>
    <label style={{
      fontSize: 12, fontWeight: 600, letterSpacing: "0.08em",
      textTransform: "uppercase", color: "var(--stone)",
      display: "flex", alignItems: "center", gap: 4
    }}>
      {label}
      {required && <span style={{ color: "var(--saffron)" }}>*</span>}
    </label>
    {children}
    {error
      ? <span style={{ fontSize: 12, color: "#c0392b" }}>{error}</span>
      : hint && <span style={{ fontSize: 12, color: "var(--stone)", opacity: 0.7 }}>{hint}</span>
    }
  </div>
);

const ProgressBar = ({ current, total }) => (
  <div style={{ display: "flex", gap: 6, marginBottom: 24 }}>
    {Array.from({ length: total }).map((_, i) => (
      <div key={i} style={{
        flex: 1, height: 3, borderRadius: 2,
        background: i <= current ? "var(--saffron)" : "var(--hairline)",
        transition: "background 300ms"
      }} />
    ))}
  </div>
);

const TOTAL = 3;
const MSG_LIMIT = 500;

const EMPTY = {
  name: "", email: "", phone: "", party: "",
  constituency: "", campaignType: "", budget: "", timeline: "",
  message: "", contactPref: "email", source: ""
};

const ApplyModal = ({ open, onClose }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState(EMPTY);
  const [errors, setErrors] = React.useState({});

  React.useEffect(() => {
    if (!open) { setStep(0); setData(EMPTY); setErrors({}); }
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const clearErr = k => setErrors(e => { const n = { ...e }; delete n[k]; return n; });

  const isEmail = v => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
  const isPhone = v => /^[+\d\s\-()\.ऀ-ॿ]{7,16}$/.test(v.trim());

  const validate0 = () => {
    const e = {};
    if (!data.name.trim())              e.name  = "Name is required.";
    if (!data.email.trim())             e.email = "Email is required.";
    else if (!isEmail(data.email))      e.email = "Enter a valid email address.";
    if (!data.phone.trim())             e.phone = "Phone number is required.";
    else if (!isPhone(data.phone))      e.phone = "Enter a valid phone number.";
    setErrors(e);
    return !Object.keys(e).length;
  };

  const validate1 = () => {
    const e = {};
    if (!data.campaignType) e.campaignType = "Please select a campaign type.";
    setErrors(e);
    return !Object.keys(e).length;
  };

  const next = () => {
    if (step === 0 && validate0()) setStep(1);
    else if (step === 1 && validate1()) setStep(2);
    else if (step === 2) setStep(3);
  };

  const titles = ["Tell us about yourself.", "About your campaign.", "What do you need?"];
  const done = step === TOTAL;

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(8,26,36,0.6)", backdropFilter: "blur(4px)",
        display: "flex", alignItems: "flex-start", justifyContent: "center",
        padding: "40px 24px", overflowY: "auto"
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: "var(--cream)", borderRadius: 6, padding: "36px 36px 32px",
          width: "min(580px, 100%)", boxShadow: "0 20px 60px -10px rgba(8,26,36,0.4)",
          margin: "auto"
        }}
      >
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
          <div style={{ flex: 1, paddingRight: 16 }}>
            <div style={{
              fontSize: 11, fontWeight: 600, letterSpacing: "0.12em",
              textTransform: "uppercase", color: "var(--gold)", marginBottom: 6
            }}>
              {done ? "Inquiry received" : `Step ${step + 1} of ${TOTAL}`}
            </div>
            <h3 style={{
              fontFamily: "var(--font-display)", fontSize: 28,
              fontWeight: 600, letterSpacing: "-0.02em", margin: 0, lineHeight: 1.2
            }}>
              {done ? "We'll be in touch within 24 hours." : titles[step]}
            </h3>
          </div>
          <button
            onClick={onClose}
            aria-label="Close"
            style={{
              border: "1px solid var(--hairline)", background: "transparent",
              width: 36, height: 36, borderRadius: 2, cursor: "pointer",
              color: "var(--ink)", display: "flex", alignItems: "center",
              justifyContent: "center", flexShrink: 0
            }}
          >
            <Icon name="x" size={18}/>
          </button>
        </div>

        {!done && <ProgressBar current={step} total={TOTAL} />}

        {/* ── Step 1: About you ── */}
        {step === 0 && (
          <>
            <div className="form-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 16px" }}>
              <Field label="Full name" required error={errors.name}>
                <SmartInput
                  value={data.name}
                  onChange={e => { set("name", e.target.value); clearErr("name"); }}
                  placeholder="Candidate or contact name"
                  error={errors.name}
                />
              </Field>
              <Field label="Party / Organization">
                <SmartInput
                  value={data.party}
                  onChange={e => set("party", e.target.value)}
                  placeholder="Party or organization"
                />
              </Field>
            </div>
            <Field label="Email address" required error={errors.email}>
              <SmartInput
                type="email"
                value={data.email}
                onChange={e => { set("email", e.target.value); clearErr("email"); }}
                placeholder="you@example.com"
                error={errors.email}
              />
            </Field>
            <Field label="Phone number" required error={errors.phone} hint="Include country code — e.g. +91 98765 43210">
              <SmartInput
                type="tel"
                value={data.phone}
                onChange={e => { set("phone", e.target.value); clearErr("phone"); }}
                placeholder="+91 98765 43210"
                error={errors.phone}
              />
            </Field>
            <div style={{ marginTop: 8, display: "flex", justifyContent: "flex-end" }}>
              <Button variant="primary" onClick={next}>Continue</Button>
            </div>
          </>
        )}

        {/* ── Step 2: Campaign ── */}
        {step === 1 && (
          <>
            <Field label="Type of campaign" required error={errors.campaignType}>
              <SmartInput
                as="select"
                value={data.campaignType}
                onChange={e => { set("campaignType", e.target.value); clearErr("campaignType"); }}
                error={errors.campaignType}
              >
                <option value="">Select campaign type</option>
                <option>Assembly Elections</option>
                <option>Lok Sabha Elections</option>
                <option>Corporation / Municipal Elections</option>
                <option>Political Branding</option>
                <option>Digital Campaign</option>
                <option>Ground Campaign</option>
                <option>Research &amp; Surveys</option>
                <option>Other</option>
              </SmartInput>
            </Field>
            <Field label="Constituency / Region">
              <SmartInput
                value={data.constituency}
                onChange={e => set("constituency", e.target.value)}
                placeholder="e.g. Hadapsar Assembly, Pune"
              />
            </Field>
            <div className="form-2col" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 16px" }}>
              <Field label="Estimated budget">
                <SmartInput
                  as="select"
                  value={data.budget}
                  onChange={e => set("budget", e.target.value)}
                >
                  <option value="">Select range</option>
                  <option>Under ₹5 Lakh</option>
                  <option>₹5 – ₹20 Lakh</option>
                  <option>₹20 – ₹50 Lakh</option>
                  <option>₹50 Lakh – ₹1 Crore</option>
                  <option>Over ₹1 Crore</option>
                  <option>Prefer not to say</option>
                </SmartInput>
              </Field>
              <Field label="Election / Start date">
                <SmartInput
                  type="date"
                  value={data.timeline}
                  onChange={e => set("timeline", e.target.value)}
                />
              </Field>
            </div>
            <div style={{ marginTop: 8, display: "flex", justifyContent: "space-between" }}>
              <Button variant="ghost" arrow={false} onClick={() => setStep(0)}>← Back</Button>
              <Button variant="primary" onClick={next}>Continue</Button>
            </div>
          </>
        )}

        {/* ── Step 3: Requirements ── */}
        {step === 2 && (
          <>
            <Field
              label="Tell us about your requirements"
              hint={`${data.message.length} / ${MSG_LIMIT} characters`}
            >
              <SmartInput
                as="textarea"
                value={data.message}
                onChange={e => { if (e.target.value.length <= MSG_LIMIT) set("message", e.target.value); }}
                rows={4}
                style={{ resize: "vertical" }}
                placeholder="Describe your campaign goals, timeline, and any specific needs..."
              />
            </Field>
            <Field label="Preferred contact method">
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                {[
                  { val: "email",    label: "Email"    },
                  { val: "phone",    label: "Phone"    },
                  { val: "whatsapp", label: "WhatsApp" },
                ].map(({ val, label }) => {
                  const active = data.contactPref === val;
                  return (
                    <label key={val} style={{
                      display: "flex", alignItems: "center", gap: 7,
                      cursor: "pointer", fontSize: 14,
                      fontWeight: active ? 600 : 400,
                      padding: "8px 14px", borderRadius: 2,
                      border: `1px solid ${active ? "var(--teal)" : "var(--hairline)"}`,
                      background: active ? "rgba(0,80,90,0.06)" : "transparent",
                      transition: "all 150ms", userSelect: "none"
                    }}>
                      <input
                        type="radio"
                        name="contactPref"
                        value={val}
                        checked={active}
                        onChange={() => set("contactPref", val)}
                        style={{ accentColor: "var(--teal)", margin: 0 }}
                      />
                      {label}
                    </label>
                  );
                })}
              </div>
            </Field>
            <Field label="How did you hear about us?">
              <SmartInput
                as="select"
                value={data.source}
                onChange={e => set("source", e.target.value)}
              >
                <option value="">Select an option</option>
                <option>Referral / Word of mouth</option>
                <option>Social media</option>
                <option>News / Press coverage</option>
                <option>Google Search</option>
                <option>Previous client</option>
                <option>Other</option>
              </SmartInput>
            </Field>
            <div style={{ marginTop: 8, display: "flex", justifyContent: "space-between" }}>
              <Button variant="ghost" arrow={false} onClick={() => setStep(1)}>← Back</Button>
              <Button variant="primary" onClick={next}>Submit inquiry</Button>
            </div>
          </>
        )}

        {/* ── Confirmation ── */}
        {done && (
          <>
            <div style={{
              background: "rgba(0,80,90,0.07)", borderRadius: 4,
              padding: "18px 20px", marginBottom: 20,
              borderLeft: "3px solid var(--teal)"
            }}>
              <p style={{ fontSize: 16, color: "var(--stone)", lineHeight: 1.6, margin: 0 }}>
                Thanks,{" "}
                <strong style={{ color: "var(--ink)" }}>{data.name || "prospective client"}</strong>.
                Your inquiry for a{" "}
                <strong style={{ color: "var(--ink)" }}>{data.campaignType || "campaign"}</strong>
                {data.constituency && (
                  <> in <strong style={{ color: "var(--ink)" }}>{data.constituency}</strong></>
                )}{" "}
                has been received.
              </p>
              {data.email && (
                <p style={{ fontSize: 13, color: "var(--stone)", margin: "8px 0 0", opacity: 0.85 }}>
                  A confirmation has been sent to <strong>{data.email}</strong>.
                </p>
              )}
            </div>
            <p style={{ fontSize: 15, color: "var(--stone)", lineHeight: 1.55, margin: "0 0 24px" }}>
              A member of our team will reach out within 24 hours via your preferred contact method.
            </p>
            <Button variant="primary" onClick={onClose}>Back to site</Button>
          </>
        )}
      </div>
    </div>
  );
};

window.ApplyModal = ApplyModal;
