/* =====================================================================
   EndSurvey — end-of-paper survey.
   Exactly five fields:
     1. role                  (required, select)
     2. which section landed  (required, multiselect)
     3. strongest pushback    (open text)
     4. talk to Alex?         (yes / no)
     5. email                 (shown only if yes)
   Persists draft + submission to localStorage. Exports: window.EndSurvey
   ===================================================================== */
(function () {
  const { useState, useEffect } = React;

  const ROLES = [
    "SRE / Platform engineer",
    "Robotics / Controls engineer",
    "Engineering leadership",
    "Founder / Exec",
    "Infrastructure / Data center",
    "Investor / Analyst",
    "Other",
  ];

  const KEY = "whooperates.survey";
  const load = () => { try { return JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) { return {}; } };
  const persist = (v) => { try { localStorage.setItem(KEY, JSON.stringify(v)); } catch (e) {} };

  function EndSurvey({ sections }) {
    const saved = load();
    const [role, setRole] = useState(saved.role || "");
    const [landed, setLanded] = useState(saved.landed || []);
    const [pushback, setPushback] = useState(saved.pushback || "");
    const [talk, setTalk] = useState(saved.talk || "");
    const [email, setEmail] = useState(saved.email || "");
    const [submitted, setSubmitted] = useState(saved.submitted || false);
    const [errors, setErrors] = useState({});

    useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

    // draft autosave
    useEffect(() => {
      if (submitted) return;
      persist({ role, landed, pushback, talk, email, submitted: false });
    }, [role, landed, pushback, talk, email, submitted]);

    const toggleLanded = (id) => {
      setLanded((cur) => cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]);
    };

    const emailValid = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

    const submit = (e) => {
      e.preventDefault();
      const err = {};
      if (!role) err.role = "Pick the closest role.";
      if (landed.length === 0) err.landed = "Pick at least one section.";
      if (talk === "yes" && !emailValid(email)) err.email = "Add an email so Alex can reach you.";
      setErrors(err);
      if (Object.keys(err).length) {
        const first = document.querySelector(".wp-field.has-error [tabindex], .wp-field.has-error input, .wp-field.has-error select, .wp-field.has-error textarea, .wp-field.has-error button");
        if (first) first.focus();
        return;
      }
      const payload = { role, landed, pushback, talk, email, submitted: true, at: new Date().toISOString() };
      persist(payload);
      setSubmitted(true);
      if (window.lucide) setTimeout(() => window.lucide.createIcons(), 0);
    };

    if (submitted) {
      return (
        <div className="wp-survey-done ui" role="status">
          <div className="wp-survey-done-mark"><i data-lucide="check" aria-hidden="true"></i></div>
          <h3 className="wp-survey-done-title">Logged. Thank you.</h3>
          <p className="wp-survey-done-body">
            Your read of <strong>Who Operates the Fleet's Compute?</strong> is recorded
            {talk === "yes" ? <> — Alex will follow up at <span className="mono">{email}</span>.</> : <>.</>}
          </p>
          <button type="button" className="wp-link-btn" onClick={() => { setSubmitted(false); persist({ role, landed, pushback, talk, email, submitted: false }); }}>
            Edit response
          </button>
        </div>
      );
    }

    return (
      <form className="wp-survey ui" onSubmit={submit} noValidate>
        {/* 1. Role */}
        <div className={"wp-field" + (errors.role ? " has-error" : "")}>
          <label className="wp-label" htmlFor="sv-role">
            Your role <span className="wp-req" aria-hidden="true">*</span>
          </label>
          <div className="wp-select-wrap">
            <select id="sv-role" className="wp-select" value={role}
                    aria-required="true" aria-invalid={!!errors.role}
                    onChange={(e) => setRole(e.target.value)}>
              <option value="" disabled>Select your role…</option>
              {ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
            </select>
            <i data-lucide="chevron-down" className="wp-select-chev" aria-hidden="true"></i>
          </div>
          {errors.role && <span className="wp-error">{errors.role}</span>}
        </div>

        {/* 2. Which section landed (multiselect) */}
        <div className={"wp-field" + (errors.landed ? " has-error" : "")}>
          <span className="wp-label" id="sv-landed-label">
            Which section landed most? <span className="wp-req" aria-hidden="true">*</span>
            <span className="wp-label-hint">Select all that apply</span>
          </span>
          <div className="wp-chipset" role="group" aria-labelledby="sv-landed-label">
            {sections.map((s) => (
              <button key={s.id} type="button"
                      className={"wp-multichip" + (landed.includes(s.id) ? " is-on" : "")}
                      aria-pressed={landed.includes(s.id)}
                      onClick={() => toggleLanded(s.id)}>
                <span className="wp-multichip-num mono">{s.num}</span>
                {s.title}
                {landed.includes(s.id) && <i data-lucide="check" className="wp-multichip-check" aria-hidden="true"></i>}
              </button>
            ))}
          </div>
          {errors.landed && <span className="wp-error">{errors.landed}</span>}
        </div>

        {/* 3. Strongest pushback */}
        <div className="wp-field">
          <label className="wp-label" htmlFor="sv-pushback">
            Strongest pushback <span className="wp-label-hint">Optional</span>
          </label>
          <textarea id="sv-pushback" className="wp-textarea" rows={3}
                    placeholder="Where does the argument not hold for your fleet?"
                    value={pushback} onChange={(e) => setPushback(e.target.value)}></textarea>
        </div>

        {/* 4. Talk to Alex? */}
        <div className="wp-field">
          <span className="wp-label" id="sv-talk-label">Want to talk to Alex about your fleet?</span>
          <div className="wp-toggle" role="group" aria-labelledby="sv-talk-label">
            {["yes", "no"].map((v) => (
              <button key={v} type="button"
                      className={"wp-toggle-btn" + (talk === v ? " is-on" : "")}
                      aria-pressed={talk === v}
                      onClick={() => setTalk(v)}>
                {v === "yes" ? "Yes" : "No"}
              </button>
            ))}
          </div>
        </div>

        {/* 5. Email (only if yes) */}
        {talk === "yes" && (
          <div className={"wp-field wp-field-email" + (errors.email ? " has-error" : "")}>
            <label className="wp-label" htmlFor="sv-email">
              Email <span className="wp-req" aria-hidden="true">*</span>
            </label>
            <input id="sv-email" type="email" className="wp-input" inputMode="email"
                   placeholder="you@yourfleet.io" value={email}
                   aria-required="true" aria-invalid={!!errors.email}
                   onChange={(e) => setEmail(e.target.value)} />
            {errors.email && <span className="wp-error">{errors.email}</span>}
          </div>
        )}

        <div className="wp-survey-foot">
          <button type="submit" className="wp-btn-primary">
            Submit response <i data-lucide="arrow-right" aria-hidden="true"></i>
          </button>
          <span className="wp-survey-note">Stored locally in this demo — nothing leaves your browser.</span>
        </div>
      </form>
    );
  }

  window.EndSurvey = EndSurvey;
})();
