/* global React, window */
/* Submit Intake — the guided form behind the home screen's "Submit Intake" pill.
   It is the second on-ramp into the same pipeline the composer feeds: it does not
   publish anything itself, it just hands `onSubmit` a brief, a calendar moment and
   a timing tier, and the home screen forwards those to the ordinary
   home → designing → intake route. The sections follow the MakerSights research
   intake framework (decision context, objective, audience, inputs, constraints)
   so what a merchant fills in here is the same shape ops already asks for. */
const { useState: ifS, useRef: ifR, useEffect: ifE } = React;

const IF_STEPS = [
  { id: "decision", n: "01", t: "Decision context", d: "The business decision this study has to support." },
  { id: "objective", n: "02", t: "Research objective", d: "What the study must answer, and what you already believe." },
  { id: "audience", n: "03", t: "Audience", d: "Who the results have to represent." },
  { id: "inputs", n: "04", t: "Study inputs", d: "What you're putting in front of consumers." },
  { id: "constraints", n: "05", t: "Timing and service", d: "When you need it, and what you need back." },
  { id: "review", n: "06", t: "Review", d: "Read it back, then we'll design the study." }
];

const IF_MARKETS = ["US", "UK", "France", "Germany", "Canada", "China"];
const IF_CUTS = ["Age", "Gender", "New vs. existing", "Heavy vs. light users", "Market", "Price sensitivity"];
const IF_DISPLAY = ["Side by side", "One at a time", "Several images per product"];
const IF_TIMING = [
  { id: "quick", label: "Same day" },
  { id: "standard", label: "This week" },
  { id: "extended", label: "Two to three weeks" }
];
const IF_SERVICE = ["Survey only", "Survey and insight report", "Report and readout"];

const IF_BLANK = {
  decision: "", owner: "", moment: null,
  primary: "", hypothesis: "", secondary: "",
  audience: "", markets: [], cuts: [],
  stimuli: "", count: "", benchmarks: "", display: "",
  timing: "", service: "", notes: ""
};

/* One worked answer per field, so a demo can be walked end to end without anyone
   typing. It is Under Armour's line-adoption moment because that is the one the
   room recognises fastest. */
const IF_EXAMPLE = {
  decision: "We have to decide which 12 of the 20 Spring '28 women's training styles carry into the global line, and which are market-specific.",
  owner: "Dan Leahy, VP Merchandising — needs the call by 12 October to lock the line plan.",
  moment: "line",
  primary: "Which styles earn a place in the global line, and which only work in one region?",
  hypothesis: "We think the seamless tops travel globally and the heavier fleece is a US and Canada story only.",
  secondary: "Where does price stop being the reason someone walks away?",
  audience: "Women 18–44 who train at least twice a week and have bought performance apparel in the last six months.",
  markets: ["US", "UK", "Germany"],
  cuts: ["Age", "Market", "New vs. existing"],
  stimuli: "20 Spring '28 women's training styles — front and back shots on white, plus colorway options.",
  count: "20 styles",
  benchmarks: "Three Spring '27 carryover styles that sold through above plan.",
  display: "Side by side",
  timing: "standard",
  service: "Survey and insight report",
  notes: "Same audience definition as the Spring '27 read so the two are comparable."
};

/* The explanatory line each question used to carry, folded into an (i) next to
   the label. Reuses the repo's `data-tip` ::after tooltip (finding-curation.css)
   rather than adding a second tooltip system; the click toggle is there so the
   copy is reachable without a hover, and aria-label carries it to a reader. */
function IFInfo({ tip }) {
  const [open, setOpen] = ifS(false);
  if (!tip) return null;
  return (
    <button type="button" className={"ifm-i" + (open ? " on" : "")} data-tip={tip}
      aria-label={tip} aria-expanded={open}
      onClick={(e) => { e.preventDefault(); e.stopPropagation(); setOpen(v => !v); }}
      onBlur={() => setOpen(false)}>
      <i className="ti ti-info-circle"></i>
    </button>
  );
}

/* `hintInline` keeps a hint as a visible line instead of an info bubble — used
   only where the copy is example guidance for the field itself, not a note
   about the question. */
function IFField({ label, hint, hintInline, essential, children }) {
  return (
    <label className="ifm-f">
      <span className="ifm-f__l">
        {label}
        {essential && <em className="ifm-f__e">Essential</em>}
        {!hintInline && <IFInfo tip={hint} />}
      </span>
      {hintInline && hint && <span className="ifm-f__h">{hint}</span>}
      {children}
    </label>
  );
}

function IFChips({ options, value, onPick, multi }) {
  const on = (id) => multi ? (value || []).indexOf(id) > -1 : value === id;
  return (
    <div className="ifm-chips">
      {options.map(o => {
        const id = typeof o === "string" ? o : o.id;
        const label = typeof o === "string" ? o : o.label;
        const sub = typeof o === "string" ? null : o.sub;
        return (
          <button type="button" key={id} className={"ifm-chip" + (on(id) ? " on" : "")}
            onClick={() => {
              if (!multi) return onPick(value === id ? "" : id);
              const v = value || [];
              onPick(v.indexOf(id) > -1 ? v.filter(x => x !== id) : [...v, id]);
            }}>
            {o.icon && <i className={"ti ti-" + o.icon}></i>}
            <span className="ifm-chip__l">{label}</span>
            {sub && <span className="ifm-chip__s">{sub}</span>}
          </button>
        );
      })}
    </div>
  );
}

/* The brief the loading and intake screens read. It is prose, not a form dump,
   because downstream it renders as the merchant's own opening chat message —
   a bulleted record of the form would read as a machine talking to itself. */
function ifBrief(f) {
  /* Answers get embedded mid-sentence, so a field the merchant ended with a
     full stop has to lose it or the brief reads "…six months. in US, UK." */
  const cut = (s) => (s || "").trim().replace(/[.;,\s]+$/, "");
  const end = (s) => { const v = (s || "").trim(); return v && !/[.!?]$/.test(v) ? v + "." : v; };
  const timing = IF_TIMING.find(t => t.id === f.timing);
  const bits = [];
  if (cut(f.decision)) bits.push(end(f.decision));
  if (cut(f.primary)) bits.push("The question we have to answer is: " + end(f.primary));
  if (cut(f.hypothesis)) bits.push(end("Going in, we think " + cut(f.hypothesis).replace(/^we (think|believe) /i, "")));
  const aud = [cut(f.audience), f.markets.length ? f.markets.join(", ") : ""].filter(Boolean).join(" in ");
  if (aud) bits.push("It needs to read on " + aud + ".");
  if (f.cuts.length) bits.push("Cut it by " + f.cuts.join(", ").toLowerCase() + ".");
  const stim = [cut(f.count), cut(f.stimuli)].filter(Boolean).join(" — ");
  if (stim) bits.push("We're putting " + stim + " in front of them.");
  if (cut(f.benchmarks)) bits.push("Benchmarks: " + end(f.benchmarks));
  if (timing) bits.push("We need it " + timing.label.toLowerCase() + ".");
  if (cut(f.notes)) bits.push(end(f.notes));
  return bits.join(" ");
}

function IFReviewRow({ label, value, onJump }) {
  const filled = Array.isArray(value) ? value.length > 0 : !!(value && String(value).trim());
  const shown = Array.isArray(value) ? value.join(", ") : value;
  return (
    <button type="button" className={"ifm-rv" + (filled ? "" : " is-empty")} onClick={onJump}>
      <span className="ifm-rv__l">{label}</span>
      <span className="ifm-rv__v">{filled ? shown : "Not answered"}</span>
      <i className="ti ti-pencil"></i>
    </button>
  );
}

function EHIntakeModal({ onClose, onSubmit }) {
  const [i, setI] = ifS(0);
  const [f, setF] = ifS(IF_BLANK);
  const bodyRef = ifR(null);
  const set = (k) => (v) => setF(p => ({ ...p, [k]: v }));
  const txt = (k) => (e) => setF(p => ({ ...p, [k]: e.target.value }));
  const step = IF_STEPS[i];
  const last = i === IF_STEPS.length - 1;
  const moments = (window.EH && window.EH.moments) || [];
  const momentOpts = moments.map(m => ({ id: m.id, label: m.title, icon: m.icon }));

  ifE(() => { if (bodyRef.current) bodyRef.current.scrollTop = 0; }, [i]);
  ifE(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);

  const submit = () => onSubmit({ brief: ifBrief(f), moment: f.moment || null, tier: f.timing || null, fields: f });

  return (
    <div className="ifm-overlay" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="ifm-panel" role="dialog" aria-modal="true" aria-label="Study intake">
        <div className="ifm-hd">
          <div className="ifm-hd__t">
            <b>Study intake</b>
            <span>Six short sections. We'll turn the answers into a designed study.</span>
          </div>
          <button className="ifm-ex" type="button" onClick={() => setF(IF_EXAMPLE)}>
            <i className="ti ti-wand"></i>Fill with an example
          </button>
          <button className="ifm-x" type="button" onClick={onClose} aria-label="Close"><i className="ti ti-x"></i></button>
        </div>

        <div className="ifm-body">
          <div className="ifm-rail">
            {IF_STEPS.map((s, k) => (
              <button type="button" key={s.id} className={"ifm-rail__s" + (k === i ? " on" : "") + (k < i ? " done" : "")} onClick={() => setI(k)}>
                <span className="ifm-rail__n">{k < i ? <i className="ti ti-check"></i> : s.n}</span>
                <span className="ifm-rail__l">{s.t}</span>
              </button>
            ))}
          </div>

          <div className="ifm-main" ref={bodyRef}>
            <div className="ifm-step">
              <div className="ifm-step__k">Section {step.n} of 06</div>
              <h3 className="ifm-step__t">{step.t}<IFInfo tip={step.d} /></h3>
            </div>

            {step.id === "decision" && (
              <React.Fragment>
                {/* The one hint that stays visible: it is worked example copy for
                    the field, not a note about the question, so it reads as
                    guidance in place rather than as something to go and find. */}
                <IFField label="What decision are you trying to make?" essential hintInline
                  hint="Name the choice, not the topic — which styles, which price, which name.">
                  <textarea className="ifm-ta" rows={3} value={f.decision} onChange={txt("decision")}
                    placeholder="We have to decide which of the Spring '28 styles carry into the global line…" />
                </IFField>
                <IFField label="Who makes the call, and by when?" essential>
                  <input className="ifm-in" value={f.owner} onChange={txt("owner")}
                    placeholder="Dan Leahy, VP Merchandising — needs it by 12 October" />
                </IFField>
                <IFField label="Which moment in the calendar is this?"
                  hint="This sets the shape of the report you get back.">
                  <IFChips options={momentOpts} value={f.moment} onPick={v => setF(p => ({ ...p, moment: v || null }))} />
                </IFField>
              </React.Fragment>
            )}

            {step.id === "objective" && (
              <React.Fragment>
                <IFField label="What is the primary question the research must answer?" essential>
                  <textarea className="ifm-ta" rows={3} value={f.primary} onChange={txt("primary")}
                    placeholder="Which styles earn a place in the global line, and which only work in one region?" />
                </IFField>
                <IFField label="What do you already believe to be true?" essential
                  hint="Even if you can't prove it yet. We'll design the study to test it.">
                  <textarea className="ifm-ta" rows={2} value={f.hypothesis} onChange={txt("hypothesis")}
                    placeholder="We think the seamless tops travel globally and the fleece is a US story…" />
                </IFField>
                <IFField label="Anything useful but secondary?" hint="Up to two more questions.">
                  <input className="ifm-in" value={f.secondary} onChange={txt("secondary")}
                    placeholder="Where does price stop being the reason someone walks away?" />
                </IFField>
              </React.Fragment>
            )}

            {step.id === "audience" && (
              <React.Fragment>
                <IFField label="Who are you trying to understand?" essential
                  hint="Demographics, category behavior, anything that has to screen in or out.">
                  <textarea className="ifm-ta" rows={3} value={f.audience} onChange={txt("audience")}
                    placeholder="Women 18–44 who train at least twice a week and bought performance apparel in the last six months" />
                </IFField>
                <IFField label="Which markets?" essential>
                  <IFChips options={IF_MARKETS} value={f.markets} onPick={set("markets")} multi />
                </IFField>
                <IFField label="What do you want to compare in the analysis?">
                  <IFChips options={IF_CUTS} value={f.cuts} onPick={set("cuts")} multi />
                </IFField>
              </React.Fragment>
            )}

            {step.id === "inputs" && (
              <React.Fragment>
                <IFField label="What are you putting in front of consumers?" essential
                  hint="Products, concepts, imagery, messaging — and what state the assets are in.">
                  <textarea className="ifm-ta" rows={3} value={f.stimuli} onChange={txt("stimuli")}
                    placeholder="20 Spring '28 women's training styles — front and back shots on white" />
                </IFField>
                <div className="ifm-row">
                  <IFField label="How many items?">
                    <input className="ifm-in" value={f.count} onChange={txt("count")} placeholder="20 styles" />
                  </IFField>
                  <IFField label="Benchmarks or competitors to include?">
                    <input className="ifm-in" value={f.benchmarks} onChange={txt("benchmarks")} placeholder="Three Spring '27 carryovers" />
                  </IFField>
                </div>
                <IFField label="How should they be shown?">
                  <IFChips options={IF_DISPLAY} value={f.display} onPick={set("display")} />
                </IFField>
              </React.Fragment>
            )}

            {step.id === "constraints" && (
              <React.Fragment>
                <IFField label="When do you need the results?" essential
                  hint="This is the one input that decides whether we field Twins, shoppers, or both.">
                  <IFChips options={IF_TIMING} value={f.timing} onPick={set("timing")} />
                </IFField>
                <IFField label="What do you need back?" essential>
                  <IFChips options={IF_SERVICE} value={f.service} onPick={set("service")} />
                </IFField>
                <IFField label="Anything else we should know?"
                  hint="Prior studies to match, constraints, conflicts, sensitivities.">
                  <textarea className="ifm-ta" rows={2} value={f.notes} onChange={txt("notes")}
                    placeholder="Same audience definition as the Spring '27 read so the two are comparable" />
                </IFField>
              </React.Fragment>
            )}

            {step.id === "review" && (
              <React.Fragment>
                <div className="ifm-rvg">
                  <div className="ifm-rvg__h">Decision context</div>
                  <IFReviewRow label="Decision" value={f.decision} onJump={() => setI(0)} />
                  <IFReviewRow label="Decision-maker" value={f.owner} onJump={() => setI(0)} />
                  <IFReviewRow label="Moment" value={(moments.find(m => m.id === f.moment) || {}).title || ""} onJump={() => setI(0)} />
                  <div className="ifm-rvg__h">Research objective</div>
                  <IFReviewRow label="Primary question" value={f.primary} onJump={() => setI(1)} />
                  <IFReviewRow label="Hypothesis" value={f.hypothesis} onJump={() => setI(1)} />
                  <div className="ifm-rvg__h">Audience</div>
                  <IFReviewRow label="Who" value={f.audience} onJump={() => setI(2)} />
                  <IFReviewRow label="Markets" value={f.markets} onJump={() => setI(2)} />
                  <IFReviewRow label="Compare" value={f.cuts} onJump={() => setI(2)} />
                  <div className="ifm-rvg__h">Study inputs</div>
                  <IFReviewRow label="Stimuli" value={f.stimuli} onJump={() => setI(3)} />
                  <IFReviewRow label="Benchmarks" value={f.benchmarks} onJump={() => setI(3)} />
                  <div className="ifm-rvg__h">Timing and service</div>
                  <IFReviewRow label="Needed" value={(IF_TIMING.find(t => t.id === f.timing) || {}).label || ""} onJump={() => setI(4)} />
                  <IFReviewRow label="Deliverable" value={f.service} onJump={() => setI(4)} />
                </div>
                <div className="ifm-note"><i className="ti ti-info-circle"></i>Nothing here is locked. You'll be able to change the questions, the audience and the assets on the study itself.</div>
              </React.Fragment>
            )}
          </div>
        </div>

        <div className="ifm-ft">
          <button type="button" className="ifm-b" onClick={() => (i === 0 ? onClose() : setI(i - 1))}>
            {i === 0 ? "Cancel" : <React.Fragment><i className="ti ti-arrow-left"></i>Back</React.Fragment>}
          </button>
          <span className="ifm-ft__sp"></span>
          <span className="ifm-ft__n">{step.n} / 06</span>
          {last ? (
            <button type="button" className="ifm-b ifm-b--p" onClick={submit}>Create a Study<i className="ti ti-arrow-right"></i></button>
          ) : (
            <button type="button" className="ifm-b ifm-b--p" onClick={() => setI(i + 1)}>Next<i className="ti ti-arrow-right"></i></button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EHIntakeModal });
