// JM&W — consultation flow (3-step intake). Mounts into #consult-app.
// (Tweaks design panel removed for production; design defaults baked into CSS/HTML.)
const { useState, useEffect } = React;

const JMW_CASES = [
  { id: "business",   title: "Business law",        sub: "Contracts, disputes, governance" },
  { id: "biz-bk",     title: "Business bankruptcy", sub: "Chapter 11, workouts, creditors" },
  { id: "personal-bk",title: "Personal bankruptcy", sub: "Chapter 7 & 13, a clean start" },
  { id: "mold",       title: "Mold litigation",     sub: "Exposure, builders, insurers" },
  { id: "injury",     title: "Personal injury",     sub: "Serious accidents, serious recovery" },
  { id: "other",      title: "Something else",      sub: "Full-service — just ask" }
];
const JMW_URGENCY = ["It's urgent", "Within a month", "Planning ahead"];

function JMWConsultFlow() {
  const [step, setStep] = useState(0);
  const [needPick, setNeedPick] = useState(false);
  const [caseType, setCaseType] = useState(null);
  const [urgency, setUrgency] = useState(null);
  const [details, setDetails] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [errors, setErrors] = useState({});

  useEffect(() => {
    const onPath = (e) => {
      const map = { business: "business", personal: "injury" };
      const id = map[e.detail];
      if (id) { setCaseType(id); setStep(0); }
    };
    window.addEventListener("jmw-path", onPath);
    if (window.__jmwPath) onPath({ detail: window.__jmwPath });
    return () => window.removeEventListener("jmw-path", onPath);
  }, []);

  const validateContact = () => {
    const errs = {};
    if (!name.trim()) errs.name = "Please tell us your name.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) errs.email = "A valid email helps us reach you.";
    if (phone && phone.replace(/\D/g, "").length < 10) errs.phone = "That number looks short.";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const stepLabels = ["The matter", "The situation", "Reaching you", "Received"];

  return (
    <div className="flow">
      <div className="flow-steps" aria-hidden="true">
        {[0, 1, 2].map((i) => (
          <React.Fragment key={i}>
            <div className={"flow-step-dot" + (step >= i ? " active" : "")}></div>
            {i < 2 && <div className="flow-step-line"></div>}
          </React.Fragment>
        ))}
        <span className="flow-step-label">{String(Math.min(step, 2) + 1).padStart(2, "0")} / 03 — {stepLabels[step]}</span>
      </div>

      {step === 0 && (
        <div>
          <h3>What brings you to us?</h3>
          <p className="flow-sub">Choose the closest fit — we'll route it to the right partner.</p>
          <div className={"case-tiles" + (needPick ? " need-pick" : "")}>
            {JMW_CASES.map((c) => (
              <button key={c.id} type="button"
                className={"case-tile" + (caseType === c.id ? " selected" : "")}
                onClick={() => setCaseType(c.id)}>
                <b>{c.title}</b><span>{c.sub}</span>
              </button>
            ))}
          </div>
          <div className="flow-nav">
            <span></span>
            <button type="button" className="btn"
              onClick={() => {
                if (caseType) { setStep(1); return; }
                setNeedPick(true);
                setTimeout(() => setNeedPick(false), 1000);
              }}>Continue <span className="arr">→</span></button>
          </div>
        </div>
      )}

      {step === 1 && (
        <div>
          <h3>A few details.</h3>
          <p className="flow-sub">Two questions — both optional to answer fully, but they help.</p>
          <div className="flow-field">
            <label>How soon do you need counsel?</label>
            <div className="flow-radios">
              {JMW_URGENCY.map((u) => (
                <button key={u} type="button"
                  className={"flow-radio" + (urgency === u ? " selected" : "")}
                  onClick={() => setUrgency(u)}>{u}</button>
              ))}
            </div>
          </div>
          <div className="flow-field">
            <label>In a sentence or two, what happened?</label>
            <textarea rows="4" value={details} placeholder="Confidential — shared only with the reviewing partner."
              onChange={(e) => setDetails(e.target.value)}></textarea>
          </div>
          <div className="flow-nav">
            <button type="button" className="flow-back" onClick={() => setStep(0)}>← Back</button>
            <button type="button" className="btn" onClick={() => setStep(2)}>Continue <span className="arr">→</span></button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div>
          <h3>Where should we reach you?</h3>
          <p className="flow-sub">A partner reviews every submission. Response within one business day.*</p>
          <div className="flow-field">
            <label>Full name</label>
            <input type="text" value={name} className={errors.name ? "err" : ""}
              onChange={(e) => setName(e.target.value)} placeholder="Jane Q. Public" />
            {errors.name && <div className="err-msg">{errors.name}</div>}
          </div>
          <div className="flow-field">
            <label>Email</label>
            <input type="email" value={email} className={errors.email ? "err" : ""}
              onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" />
            {errors.email && <div className="err-msg">{errors.email}</div>}
          </div>
          <div className="flow-field">
            <label>Phone (optional)</label>
            <input type="tel" value={phone} className={errors.phone ? "err" : ""}
              onChange={(e) => setPhone(e.target.value)} placeholder="(256) 555-0123" />
            {errors.phone && <div className="err-msg">{errors.phone}</div>}
          </div>
          <div className="flow-nav">
            <button type="button" className="flow-back" onClick={() => setStep(1)}>← Back</button>
            <button type="button" className="btn" onClick={() => { if (validateContact()) setStep(3); }}>
              Submit for review <span className="arr">→</span>
            </button>
          </div>
        </div>
      )}

      {step === 3 && (
        <div className="flow-done">
          <div className="dmd">
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none"><path d="M4 12.5l5.5 5.5L20 6.5" stroke="#FFFFFF" strokeWidth="2.2" strokeLinecap="square" /></svg>
          </div>
          <h3>On the docket.</h3>
          <p>Thank you{name ? ", " + name.split(" ")[0] : ""}. Your {JMW_CASES.find((c) => c.id === caseType)?.title.toLowerCase()} matter is in front of the reviewing partner. We'll reach you at {email}.</p>
          <div style={{ marginTop: 28 }}>
            <button type="button" className="flow-back" onClick={() => { setStep(0); setCaseType(null); setUrgency(null); setDetails(""); }}>Start another inquiry</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ============ MOUNT ============ */
const jmwConsultEl = document.getElementById("consult-app");
if (jmwConsultEl) ReactDOM.createRoot(jmwConsultEl).render(<JMWConsultFlow />);
