// Confinement Flow — Modal components

const Icon = {
  Check: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12"></polyline>
    </svg>
  ),
  X: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
  ),
  Plus: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line>
    </svg>
  ),
  Arrow: () => <span className="arrow" aria-hidden="true">→</span>,
  Bell: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>
    </svg>
  ),
  Calendar: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
    </svg>
  ),
  Heart: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  ),
  Chart: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/>
    </svg>
  ),
  Mail: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/>
    </svg>
  ),
  Bed: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 9V20"/><path d="M22 20V12a2 2 0 0 0-2-2H8"/><circle cx="6" cy="12" r="2"/><path d="M2 16h20"/>
    </svg>
  ),
  Lock: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
    </svg>
  ),
};

function Modal({ open, onClose, children, wide }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);
  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={"modal" + (wide ? " wide" : "")} onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <Icon.X size={18} />
        </button>
        {children}
      </div>
    </div>
  );
}

function LoginModal({ open, onClose, onSwitchToDemo }) {
  const [form, setForm] = React.useState({ email: "", password: "" });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const [success, setSuccess] = React.useState(false);

  React.useEffect(() => {
    if (!open) {
      setForm({ email: "", password: "" });
      setErrors({}); setLoading(false); setSuccess(false);
    }
  }, [open]);

  const validate = () => {
    const e = {};
    if (!form.email) e.email = "Email is required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Please enter a valid email";
    if (!form.password) e.password = "Password is required";
    else if (form.password.length < 6) e.password = "At least 6 characters";
    return e;
  };

  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      setSuccess(true);
      setTimeout(onClose, 1400);
    }, 900);
  };

  return (
    <Modal open={open} onClose={onClose}>
      {success ? (
        <div style={{ textAlign: "center", padding: "12px 0" }}>
          <div className="success-icon"><Icon.Check size={28} /></div>
          <div className="modal-title">Welcome back</div>
          <p className="modal-sub">Taking you to your dashboard…</p>
        </div>
      ) : (
        <>
          <div className="modal-head">
            <div className="modal-title">Sign in to ConfinementFlow</div>
            <p className="modal-sub">Welcome back. Manage your centre with calm.</p>
          </div>
          <form onSubmit={submit} noValidate>
            <div className={"field" + (errors.email ? " error" : "")}>
              <label htmlFor="li-email">Email</label>
              <input
                id="li-email" type="email" autoComplete="email"
                placeholder="you@centre.my"
                value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })}
              />
              {errors.email && <div className="field-error">{errors.email}</div>}
            </div>
            <div className={"field" + (errors.password ? " error" : "")}>
              <label htmlFor="li-pw" style={{ display: "flex", justifyContent: "space-between" }}>
                <span>Password</span>
                <button type="button" className="text-link" style={{ fontSize: 12 }} onClick={(e) => e.preventDefault()}>Forgot?</button>
              </label>
              <input
                id="li-pw" type="password" autoComplete="current-password"
                placeholder="••••••••"
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
              />
              {errors.password && <div className="field-error">{errors.password}</div>}
            </div>
            <button type="submit" className="btn btn-primary btn-lg" style={{ width: "100%", justifyContent: "center", marginTop: 8 }} disabled={loading}>
              {loading ? "Signing in…" : <>Sign in <Icon.Arrow /></>}
            </button>
            <div style={{ textAlign: "center", marginTop: 18, fontSize: 13.5, color: "var(--ink-soft)" }}>
              New to ConfinementFlow?{" "}
              <button type="button" className="text-link" onClick={() => { onClose(); setTimeout(onSwitchToDemo, 150); }}>
                Request a demo
              </button>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", marginTop: 16, fontSize: 12, color: "var(--ink-mute)" }}>
              <Icon.Lock size={12} /> Secured with end-to-end encryption
            </div>
          </form>
        </>
      )}
    </Modal>
  );
}

function DemoModal({ open, onClose, prefilledPlan }) {
  const totalSteps = 4;
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    role: "", centreSize: "", name: "", email: "", phone: "", centre: "", state: "", interests: [],
  });

  React.useEffect(() => {
    if (!open) {
      setStep(1);
      setData({ role: "", centreSize: "", name: "", email: "", phone: "", centre: "", state: "", interests: [] });
    }
  }, [open]);

  React.useEffect(() => {
    if (open && prefilledPlan) {
      setData(d => ({ ...d, interests: [prefilledPlan] }));
    }
  }, [open, prefilledPlan]);

  const canNext = () => {
    if (step === 1) return !!data.role;
    if (step === 2) return !!data.centreSize;
    if (step === 3) return data.name.trim() && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email) && data.centre.trim();
    return true;
  };

  const next = () => {
    if (step < totalSteps) setStep(step + 1);
  };
  const back = () => { if (step > 1) setStep(step - 1); };

  const Stepper = () => (
    <div className="steps-bar">
      {Array.from({ length: totalSteps }).map((_, i) => (
        <div key={i} className={"pip " + (i + 1 < step ? "done" : i + 1 === step ? "current" : "")}></div>
      ))}
    </div>
  );

  const Choice = ({ value, title, sub, field, multi }) => {
    const isSel = multi
      ? data[field].includes(value)
      : data[field] === value;
    const onClick = () => {
      if (multi) {
        const arr = data[field].includes(value)
          ? data[field].filter(v => v !== value)
          : [...data[field], value];
        setData({ ...data, [field]: arr });
      } else {
        setData({ ...data, [field]: value });
      }
    };
    return (
      <button type="button" className={"choice" + (isSel ? " selected" : "")} onClick={onClick}>
        <span className="choice-title">{title}</span>
        {sub && <span className="choice-sub">{sub}</span>}
      </button>
    );
  };

  return (
    <Modal open={open} onClose={onClose} wide>
      <div className="modal-head">
        <Stepper />
        {step === 1 && <>
          <div className="modal-title">Hello — what brings you here?</div>
          <p className="modal-sub">Help us tailor the demo to your role.</p>
        </>}
        {step === 2 && <>
          <div className="modal-title">How big is your centre?</div>
          <p className="modal-sub">We'll show flows that match your scale.</p>
        </>}
        {step === 3 && <>
          <div className="modal-title">A few details, please</div>
          <p className="modal-sub">A specialist will reach out within one business day.</p>
        </>}
        {step === 4 && <>
          <div style={{ textAlign: "center" }}>
            <div className="success-icon"><Icon.Check size={28} /></div>
            <div className="modal-title">Demo request received</div>
            <p className="modal-sub">
              Terima kasih, {data.name.split(" ")[0] || "friend"}. We'll be in touch with{" "}
              <strong style={{ color: "var(--ink)" }}>{data.email}</strong> very soon.
            </p>
          </div>
        </>}
      </div>

      {step === 1 && (
        <div className="choice-grid">
          <Choice field="role" value="owner" title="Centre owner" sub="I run the business" />
          <Choice field="role" value="manager" title="Branch manager" sub="I oversee operations" />
          <Choice field="role" value="nurse" title="Lead nurse" sub="I care for mothers & babies" />
          <Choice field="role" value="other" title="Something else" sub="Consultant, partner, etc." />
        </div>
      )}

      {step === 2 && (
        <div className="choice-grid">
          <Choice field="centreSize" value="small" title="1 – 8 rooms" sub="Boutique centre" />
          <Choice field="centreSize" value="med" title="9 – 20 rooms" sub="Mid-size operation" />
          <Choice field="centreSize" value="large" title="21 – 50 rooms" sub="Established brand" />
          <Choice field="centreSize" value="multi" title="Multiple branches" sub="Group / franchise" />
        </div>
      )}

      {step === 3 && (
        <div>
          <div className="field-row">
            <div className="field">
              <label>Full name</label>
              <input value={data.name} onChange={(e) => setData({ ...data, name: e.target.value })} placeholder="Wei Ling Tan" />
            </div>
            <div className="field">
              <label>Phone</label>
              <input value={data.phone} onChange={(e) => setData({ ...data, phone: e.target.value })} placeholder="+60 12 345 6789" />
            </div>
          </div>
          <div className="field">
            <label>Work email</label>
            <input type="email" value={data.email} onChange={(e) => setData({ ...data, email: e.target.value })} placeholder="you@centre.my" />
          </div>
          <div className="field-row">
            <div className="field">
              <label>Centre name</label>
              <input value={data.centre} onChange={(e) => setData({ ...data, centre: e.target.value })} placeholder="Lotus Confinement Care" />
            </div>
            <div className="field">
              <label>State</label>
              <select value={data.state} onChange={(e) => setData({ ...data, state: e.target.value })}>
                <option value="">Select…</option>
                {["Selangor","Kuala Lumpur","Penang","Johor","Perak","Sabah","Sarawak","Other"].map(s => <option key={s}>{s}</option>)}
              </select>
            </div>
          </div>
        </div>
      )}

      {step < 4 && (
        <div className="modal-foot" style={{ marginTop: 18 }}>
          {step > 1 ? <button className="btn btn-outline" onClick={back}>Back</button> : <div style={{ flex: 1 }} />}
          <button
            className="btn btn-primary"
            onClick={step === 3 ? () => setStep(4) : next}
            disabled={!canNext()}
            style={{ opacity: canNext() ? 1 : 0.5 }}
          >
            {step === 3 ? "Submit request" : "Continue"} <Icon.Arrow />
          </button>
        </div>
      )}
      {step === 4 && (
        <div className="modal-foot" style={{ marginTop: 18, justifyContent: "center" }}>
          <button className="btn btn-primary" onClick={onClose} style={{ flex: "0 1 auto", padding: "12px 32px" }}>Close</button>
        </div>
      )}
    </Modal>
  );
}

function SubscribeModal({ open, onClose, plan, billing }) {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", centre: "" });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);
  const [apiError, setApiError] = React.useState(null);

  React.useEffect(() => {
    if (!open) {
      setStep(1);
      setForm({ name: "", email: "", phone: "", centre: "" });
      setErrors({});
      setLoading(false);
      setApiError(null);
    }
  }, [open]);

  if (!plan) return null;

  const amount = billing === "yearly" ? plan.yearly : plan.monthly;

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Name is required";
    if (!form.email) e.email = "Email is required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Enter a valid email";
    if (!form.centre.trim()) e.centre = "Centre name is required";
    return e;
  };

  const handlePay = async () => {
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) return;

    setLoading(true);
    setApiError(null);

    // Save plan so the failure banner can offer retry with the same plan
    try { localStorage.setItem("cf_pending_plan", JSON.stringify({ planId: plan.id, billing })); } catch (_) {}

    try {
      const res = await fetch("/api/create-bill", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone,
          centre: form.centre,
          planId: plan.id,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setApiError(data.error || "Could not create payment. Please try again.");
        setLoading(false);
        return;
      }
      window.location.href = data.url;
    } catch (_) {
      setApiError("Connection error. Please try again.");
      setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose}>
      {step === 1 && (
        <>
          <div className="modal-head">
            <div className="modal-title">Subscribe to {plan.name}</div>
            <p className="modal-sub">Confirm your plan and billing cycle.</p>
          </div>
          <div style={{ background: "var(--cream)", border: "1px solid var(--line-soft)", borderRadius: 14, padding: 20, marginBottom: 16 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div className="serif" style={{ fontSize: 22 }}>{plan.name}</div>
              <div>
                <span className="serif" style={{ fontSize: 32, fontWeight: 300, letterSpacing: "-0.03em" }}>
                  RM{amount}
                </span>
                <span style={{ fontSize: 13, color: "var(--ink-soft)", marginLeft: 4 }}>
                  {billing === "yearly" ? "/year" : "/month"}
                </span>
              </div>
            </div>
            <div style={{ height: 1, background: "var(--line-soft)", margin: "14px 0" }}></div>
            <div style={{ fontSize: 13, color: "var(--ink-soft)" }}>
              {billing === "yearly"
                ? "One-time annual payment. Includes onboarding & email support."
                : "Billed monthly. Includes onboarding & email support."}
            </div>
          </div>
          <button className="btn btn-primary btn-lg" style={{ width: "100%", justifyContent: "center" }} onClick={() => setStep(2)}>
            Continue <Icon.Arrow />
          </button>
        </>
      )}
      {step === 2 && (
        <>
          <div className="modal-head">
            <div className="modal-title">Your details</div>
            <p className="modal-sub">We'll attach these to your Billplz payment record.</p>
          </div>
          <div className={"field" + (errors.name ? " error" : "")}>
            <label>Full name</label>
            <input
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              placeholder="Wei Ling Tan"
            />
            {errors.name && <div className="field-error">{errors.name}</div>}
          </div>
          <div className="field">
            <label>Phone</label>
            <input
              value={form.phone}
              onChange={(e) => setForm({ ...form, phone: e.target.value })}
              placeholder="+60 12 345 6789"
            />
          </div>
          <div className={"field" + (errors.email ? " error" : "")}>
            <label>Work email</label>
            <input
              type="email"
              value={form.email}
              onChange={(e) => setForm({ ...form, email: e.target.value })}
              placeholder="you@centre.my"
            />
            {errors.email && <div className="field-error">{errors.email}</div>}
          </div>
          <div className={"field" + (errors.centre ? " error" : "")}>
            <label>Centre name</label>
            <input
              value={form.centre}
              onChange={(e) => setForm({ ...form, centre: e.target.value })}
              placeholder="Lotus Confinement Care"
            />
            {errors.centre && <div className="field-error">{errors.centre}</div>}
          </div>
          {apiError && (
            <div style={{ color: "#c0392b", fontSize: 13, marginBottom: 4, marginTop: 4 }}>{apiError}</div>
          )}
          <div className="modal-foot" style={{ marginTop: 12 }}>
            <button className="btn btn-outline" onClick={() => setStep(1)} disabled={loading}>Back</button>
            <button className="btn btn-primary" onClick={handlePay} disabled={loading}>
              {loading ? "Redirecting to Billplz…" : <>Pay RM{amount} via Billplz <Icon.Arrow /></>}
            </button>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center", marginTop: 16, fontSize: 12, color: "var(--ink-mute)" }}>
            <Icon.Lock size={12} /> Secured by Billplz
          </div>
        </>
      )}
    </Modal>
  );
}

Object.assign(window, { Modal, LoginModal, DemoModal, SubscribeModal, Icon });
