/* ============================================================
   SHLOK — Step content renderer → window.StepContent
   ============================================================ */
const { useState: useS, useEffect: useE, useRef: useR } = React;

function StepHead({ step }) {
  return (
    <div className="step-head">
      {step.eyebrow ? <div className="eyebrow">{step.eyebrow}</div> : null}
      <h1 className="q-title">{step.title}</h1>
      {step.sub ? <p className="q-sub">{step.sub}</p> : null}
      {step.microcopy ? (
        <div className="microcopy">
          <window.Icon name="sparkles" size={15} />
          {step.microcopy}
        </div>
      ) : null}
    </div>
  );
}

/* ---------- SINGLE (cards or chips) ---------- */
function SingleStep({ step, data, set, requestAdvance }) {
  const val = data[step.key];
  const [query, setQuery] = useS("");

  function pick(opt) {
    set(step.key, opt.v);
    if (step.allowOther && opt.v !== "Other") set(step.otherKey, "");
    if (step.autoAdvance) requestAdvance();
  }

  if (step.chips) {
    const filtered = step.options.filter((o) =>
      o.v.toLowerCase().includes(query.toLowerCase().trim())
    );
    const isOther = val === "Other";
    return (
      <div>
        <StepHead step={step} />
        {step.search ? (
          <div className="search">
            <window.Icon name="search" size={19} />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search your business type…"
              aria-label="Search business type"
            />
          </div>
        ) : null}
        <div className="chips">
          {filtered.map((o) => (
            <window.Chip key={o.v} opt={o} selected={val === o.v} onClick={() => pick(o)} />
          ))}
          {filtered.length === 0 ? (
            <div className="microcopy">No match — pick “Other” below to tell us.</div>
          ) : null}
        </div>
        {isOther ? (
          <div className="inlinefield">
            <div className="field-label">Tell us what kind of business (optional)</div>
            <input
              className="tinput"
              value={data[step.otherKey] || ""}
              onChange={(e) => set(step.otherKey, e.target.value)}
              placeholder="e.g. Solar installation, Travel agency…"
            />
          </div>
        ) : null}
      </div>
    );
  }

  return (
    <div>
      <StepHead step={step} />
      <div className={"grid " + (step.cols === 2 ? "cols-2" : step.long ? "" : "cols-2")}>
        {step.options.map((o) => (
          <window.OptionCard
            key={o.v}
            opt={o}
            selected={val === o.v}
            long={step.long}
            onClick={() => pick(o)}
          />
        ))}
      </div>
    </div>
  );
}

/* ---------- MULTI ---------- */
function MultiStep({ step, data, set }) {
  const arr = data[step.key] || [];
  const max = typeof step.maxSelections === "number" ? step.maxSelections : null;
  function toggle(opt) {
    set(step.key, (prev) => {
      const cur = prev || [];
      if (cur.includes(opt.v)) return cur.filter((x) => x !== opt.v);
      if (max !== null && cur.length >= max) return cur;
      return [...cur, opt.v];
    });
  }
  return (
    <div>
      <StepHead step={step} />
      <div className={"grid " + (step.cols === 1 ? "" : "cols-2")}>
        {step.options.map((o) => (
          <window.OptionCard
            key={o.v}
            opt={o}
            multi
            selected={arr.includes(o.v)}
            onClick={() => toggle(o)}
          />
        ))}
      </div>
    </div>
  );
}

/* ---------- RANK (top 3) ---------- */
function RankStep({ step, data, set }) {
  const arr = data[step.key] || [];
  const max = typeof step.maxSelections === "number" ? step.maxSelections : step.max;
  const full = arr.length >= max;
  function toggle(opt) {
    set(step.key, (prev) => {
      const cur = prev || [];
      if (cur.includes(opt.v)) return cur.filter((x) => x !== opt.v);
      if (cur.length >= max) return cur;
      return [...cur, opt.v];
    });
  }
  return (
    <div>
      <StepHead step={step} />
      <div className="grid cols-2">
        {step.options.map((o) => {
          const idx = arr.indexOf(o.v);
          const selected = idx >= 0;
          return (
            <window.OptionCard
              key={o.v}
              opt={o}
              selected={selected}
              rank={selected ? idx + 1 : null}
              disabled={!selected && full}
              onClick={() => toggle(o)}
            />
          );
        })}
      </div>
    </div>
  );
}

/* ---------- SLIDERS ---------- */
function SliderRow({ s, value, onChange }) {
  const [active, setActive] = useS(false);
  const pct = ((value - 1) / 9) * 100;
  const lo = value <= 4, hi = value >= 7;
  return (
    <div className={"slider-card" + (active ? " active" : "")}>
      <div className="slider-top">
        <span className="slider-name">
          <span className="si"><window.Icon name={s.icon} size={17} /></span>
          {s.name}
        </span>
        <span className="slider-val">{value}</span>
      </div>
      <div className="slider-rail">
        <div className="range-fill" style={{ width: `calc(${pct}% + ${13 - pct * 0.26}px)` }} />
        <input
          className="range"
          type="range"
          min="1" max="10" step="1"
          value={value}
          onChange={(e) => onChange(parseInt(e.target.value, 10))}
          onPointerDown={() => setActive(true)}
          onPointerUp={() => setActive(false)}
          onBlur={() => setActive(false)}
          aria-label={`${s.name}: ${s.lo} to ${s.hi}, currently ${value} of 10`}
        />
      </div>
      <div className="slider-ends">
        <span className={lo ? "lo-on" : ""}>{s.lo}</span>
        <span className={hi ? "hi-on" : ""}>{s.hi}</span>
      </div>
    </div>
  );
}

function SlidersStep({ step, data, set }) {
  const scores = data[step.key] || {};
  function setOne(k, v) {
    set(step.key, { ...scores, [k]: v, _touched: true });
  }
  return (
    <div>
      <StepHead step={step} />
      <div className="sliders">
        {step.sliders.map((s) => (
          <SliderRow
            key={s.key}
            s={s}
            value={typeof scores[s.key] === "number" ? scores[s.key] : 5}
            onChange={(v) => setOne(s.key, v)}
          />
        ))}
      </div>
    </div>
  );
}

/* ---------- LOSS (multi chips + optional note) ---------- */
function NoteArea({ type, text, onType, onText }) {
  return (
    <div className="inlinefield">
      <div className="note-tabs">
        <button type="button" className={"note-tab" + (type === "text" ? " on" : "")} onClick={() => onType("text")}>
          <window.Icon name="pencil" size={16} /> Type
        </button>
        <button type="button" className={"note-tab" + (type === "voice" ? " on" : "")} onClick={() => onType("voice")}>
          <window.Icon name="mic" size={16} /> Voice
        </button>
        <button type="button" className={"note-tab" + (type === "skip" ? " on" : "")} onClick={() => onType("skip")}>
          <window.Icon name="skipDots" size={16} /> Skip
        </button>
      </div>
      {type === "text" ? (
        <textarea
          className="tarea"
          value={text || ""}
          onChange={(e) => onText(e.target.value)}
          placeholder="One line is enough — what happened?"
        />
      ) : null}
      {type === "voice" ? <window.VoiceBox /> : null}
      {type === "skip" ? <div className="microcopy">No problem — we’ll skip this.</div> : null}
    </div>
  );
}

function LossStep({ step, data, set }) {
  const arr = data[step.key] || [];
  const max = typeof step.maxSelections === "number" ? step.maxSelections : null;
  const [noteType, setNoteType] = useS(data._lossNoteType || null);
  const showPrompt = arr.some((x) => step.triggers.includes(x));
  function toggle(opt) {
    set(step.key, (prev) => {
      const cur = prev || [];
      if (cur.includes(opt.v)) return cur.filter((x) => x !== opt.v);
      if (max !== null && cur.length >= max) return cur;
      return [...cur, opt.v];
    });
  }
  return (
    <div>
      <StepHead step={step} />
      <div className="chips">
        {step.options.map((o) => (
          <window.Chip key={o.v} opt={o} selected={arr.includes(o.v)} onClick={() => toggle(o)} />
        ))}
      </div>
      {showPrompt ? (
        <div className="inlinefield">
          <div className="field-label" style={{ fontSize: 15, color: "var(--text)", marginBottom: 12 }}>
            Want to quickly tell us what happened?
          </div>
          <NoteArea
            type={noteType}
            text={data[step.contextKey]}
            onType={(t) => { setNoteType(t); set("_lossNoteType", t); }}
            onText={(v) => set(step.contextKey, v)}
          />
        </div>
      ) : null}
    </div>
  );
}

/* ---------- MESSAGE (hero cards) ---------- */
function MessageStep({ step, data, set }) {
  const val = data[step.key];
  return (
    <div>
      <StepHead step={step} />
      <div className="msg-list">
        {step.options.map((o) => (
          <button
            key={o.v}
            type="button"
            className={"msg" + (val === o.v ? " sel" : "")}
            onClick={() => set(step.key, o.v)}
            aria-pressed={val === o.v}
          >
            <span className="qmark">“</span>
            <span className="mtext">{o.v}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ---------- FINAL NEED (single + optional note) ---------- */
function FinalNeedStep({ step, data, set }) {
  const val = data[step.key];
  const [noteType, setNoteType] = useS(data._finalNoteType || null);
  return (
    <div>
      <StepHead step={step} />
      <div className="grid cols-2">
        {step.options.map((o) => (
          <window.OptionCard key={o.v} opt={o} selected={val === o.v} onClick={() => set(step.key, o.v)} />
        ))}
      </div>
      <div className="inlinefield" style={{ marginTop: 22 }}>
        <div className="field-label" style={{ fontSize: 15, color: "var(--text)", marginBottom: 12 }}>
          {step.noteTitle}
        </div>
        <NoteArea
          type={noteType}
          text={data[step.noteTextKey]}
          onType={(t) => {
            setNoteType(t);
            set(step.noteTypeKey, t);
            set(step.voiceKey, t === "voice");
          }}
          onText={(v) => set(step.noteTextKey, v)}
        />
      </div>
    </div>
  );
}

/* ---------- CONTACT ---------- */
function ContactStep({ step, data, set }) {
  const perm = data[step.key];
  const showFields = perm === "yes" || perm === "maybe_later";
  return (
    <div>
      <StepHead step={step} />
      <div className="grid cols-2">
        {step.options.map((o) => (
          <window.OptionCard
            key={o.val}
            opt={o}
            selected={perm === o.val}
            onClick={() => set(step.key, o.val)}
          />
        ))}
      </div>
      {showFields ? (
        <div className="fields">
          <input className="tinput" placeholder="Your name" value={data.name || ""} onChange={(e) => set("name", e.target.value)} aria-label="Your name" />
          <input className="tinput" placeholder="Business name" value={data.business_name || ""} onChange={(e) => set("business_name", e.target.value)} aria-label="Business name" />
          <input className="tinput" placeholder="City / location" value={data.location || ""} onChange={(e) => set("location", e.target.value)} aria-label="City or location" />
          <input className="tinput full" placeholder="Phone number or email" value={data.contact || ""} onChange={(e) => set("contact", e.target.value)} aria-label="Phone or email" />
          <div className="consent full">
            <window.Icon name="shield" size={16} />
            Your details are only used for this conversation. Nothing is shared, and it’s all optional.
          </div>
        </div>
      ) : null}
    </div>
  );
}

/* ---------- Dispatcher ---------- */
function StepContent(props) {
  const t = props.step.type;
  if (t === "single") return <SingleStep {...props} />;
  if (t === "multi") return <MultiStep {...props} />;
  if (t === "rank") return <RankStep {...props} />;
  if (t === "sliders") return <SlidersStep {...props} />;
  if (t === "loss") return <LossStep {...props} />;
  if (t === "message") return <MessageStep {...props} />;
  if (t === "finalNeed") return <FinalNeedStep {...props} />;
  if (t === "contact") return <ContactStep {...props} />;
  return null;
}

window.StepContent = StepContent;
