// JM&W — Tweaks wiring + consultation flow
const { useState, useEffect } = React;

/* ============ TWEAKS ============ */

const JMW_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#9E1B3C", "#16100C", "#F4EFE5", "#A8854C"],
  "typePairing": "Caslon Authority",
  "heroIntensity": 80,
  "ctaPressure": "confident",
  "motionEnergy": 70,
  "density": "standard",
  "ambientLight": 55,
  "contrastAccent": "#A8854C"
}/*EDITMODE-END*/;

const JMW_PALETTES = {
  "docket":   ["#9E1B3C", "#16100C", "#F4EFE5", "#A8854C"],
  "midnight": ["#B12243", "#0E121C", "#EDEFF2", "#64788F"],
  "heritage": ["#84142B", "#221710", "#F6EEDC", "#8F6E3E"],
  "ember":    ["#AD2424", "#221208", "#F7ECDC", "#FF9C45"],
  "oxide":    ["#A31D38", "#0F1714", "#EFF2EA", "#58B894"]
};
const JMW_TYPES = {
  "Caslon Authority": "caslon",
  "Modern Counsel": "modern",
  "Bodoni Gravitas": "bodoni"
};
const JMW_CTA_COPY = {
  soft:      { header: "Speak with us",          hero: "Begin a conversation" },
  confident: { header: "Request a consultation", hero: "Request a consultation" },
  urgent:    { header: "Free case review",       hero: "Get help now — free review" }
};
const JMW_DENSITY = { compact: 0.72, standard: 1, grand: 1.28 };

function jmwPaletteKey(arr) {
  const first = Array.isArray(arr) ? arr[0] : arr;
  for (const k in JMW_PALETTES) if (JMW_PALETTES[k][0] === first) return k;
  return "docket";
}

function JMWTweaksApp() {
  const [t, setTweak] = useTweaks(JMW_TWEAK_DEFAULTS);
  const html = document.documentElement;

  useEffect(() => {
    html.setAttribute("data-palette", jmwPaletteKey(t.palette));
    html.setAttribute("data-type", JMW_TYPES[t.typePairing] || "caslon");
    html.setAttribute("data-cta", t.ctaPressure);
    html.style.setProperty("--knob-hero", String(t.heroIntensity / 100));
    html.style.setProperty("--knob-motion", String(t.motionEnergy / 100));
    html.style.setProperty("--density-mult", String(JMW_DENSITY[t.density] || 1));
    html.style.setProperty("--glow-strength", String(t.ambientLight / 100));
    html.style.setProperty("--color-accent-2", t.contrastAccent);
    html.classList.toggle("motion-off", t.motionEnergy === 0);
    const copy = JMW_CTA_COPY[t.ctaPressure] || JMW_CTA_COPY.confident;
    document.querySelectorAll("[data-cta-copy]").forEach((el) => {
      el.textContent = copy[el.getAttribute("data-cta-copy")] || copy.header;
    });
  }, [t]);

  return (
    <TweaksPanel>
      <TweakSection label="Brand" />
      <TweakColor label="Palette" value={t.palette}
        options={[JMW_PALETTES.docket, JMW_PALETTES.midnight, JMW_PALETTES.heritage, JMW_PALETTES.ember, JMW_PALETTES.oxide]}
        onChange={(v) => setTweak("palette", v)} />
      <TweakSelect label="Type pairing" value={t.typePairing}
        options={Object.keys(JMW_TYPES)}
        onChange={(v) => setTweak("typePairing", v)} />
      <TweakSection label="Creative knobs" />
      <TweakSlider label="--hero-intensity" value={t.heroIntensity} min={20} max={120} step={5}
        onChange={(v) => setTweak("heroIntensity", v)} />
      <TweakSlider label="--motion-energy" value={t.motionEnergy} min={0} max={100} step={5}
        onChange={(v) => setTweak("motionEnergy", v)} />
      <TweakRadio label="--cta-pressure" value={t.ctaPressure}
        options={["soft", "confident", "urgent"]}
        onChange={(v) => setTweak("ctaPressure", v)} />
      <TweakRadio label="--section-density" value={t.density}
        options={["compact", "standard", "grand"]}
        onChange={(v) => setTweak("density", v)} />
      <TweakSection label="Laboratory" />
      <TweakSlider label="--ambient-light" value={t.ambientLight} min={0} max={100} step={5}
        onChange={(v) => setTweak("ambientLight", v)} />
      <TweakColor label="Contrast accent" value={t.contrastAccent}
        options={["#A8854C", "#D8923F", "#4E8C72", "#64788F"]}
        onChange={(v) => setTweak("contrastAccent", v)} />
    </TweaksPanel>
  );
}

/* ============ CONSULTATION FLOW ============ */

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="#FFF8EE" 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 jmwTweaksRoot = document.createElement("div");
document.body.appendChild(jmwTweaksRoot);
ReactDOM.createRoot(jmwTweaksRoot).render(<JMWTweaksApp />);
const jmwConsultEl = document.getElementById("consult-app");
if (jmwConsultEl) ReactDOM.createRoot(jmwConsultEl).render(<JMWConsultFlow />);
