/* =====================================================================
   Reactions — per-section engagement widget.
   Three valenced options: Lands · Skeptical · Made me think
   + optional "add a thought" comment box with optional reader identity
   (name + email). Persists per section to localStorage.
   Saved payload shape: { choice, comment, author_name, author_email }
   Exports: window.SectionReaction
   ===================================================================== */
(function () {
  const { useState, useEffect } = React;

  const OPTIONS = [
    { id: "lands",     label: "Lands",          icon: "check-circle-2", hint: "This holds up." },
    { id: "skeptical", label: "Skeptical",      icon: "help-circle",    hint: "Not convinced yet." },
    { id: "think",     label: "Made me think",  icon: "lightbulb",      hint: "Changed how I see it." },
  ];

  const KEY = (sid) => `whooperates.react.${sid}`;
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  const emailOk = (v) => v.trim() === "" || EMAIL_RE.test(v.trim());

  function load(sid) {
    try { return JSON.parse(localStorage.getItem(KEY(sid))) || {}; }
    catch (e) { return {}; }
  }
  function save(sid, val) {
    try { localStorage.setItem(KEY(sid), JSON.stringify(val)); } catch (e) {}
    // broadcast so the survey / chrome can read aggregate signal
    window.dispatchEvent(new CustomEvent("bottleneck:reaction", { detail: { sid, ...val } }));
  }

  function SectionReaction({ sectionId, sectionTitle }) {
    const [choice, setChoice] = useState(null);
    const [comment, setComment] = useState("");
    const [authorName, setAuthorName] = useState("");
    const [authorEmail, setAuthorEmail] = useState("");
    const [emailError, setEmailError] = useState(false);
    const [open, setOpen] = useState(false);
    const [saved, setSaved] = useState(false);

    useEffect(() => {
      const v = load(sectionId);
      if (v.choice) setChoice(v.choice);
      if (v.comment) setComment(v.comment);
      if (v.author_name) setAuthorName(v.author_name);
      if (v.author_email) setAuthorEmail(v.author_email);
      if (v.comment || v.author_name || v.author_email) setOpen(true);
    }, [sectionId]);

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

    // Build the full payload from current state, with optional overrides for
    // values that just changed (state updates are async within a handler).
    const persist = (over) => {
      save(sectionId, {
        choice,
        comment,
        author_name: authorName.trim(),
        author_email: authorEmail.trim(),
        ...over,
      });
    };

    const pick = (id) => {
      const next = id === choice ? null : id;
      setChoice(next);
      persist({ choice: next });
      flash();
    };

    const commitComment = () => {
      const ok = emailOk(authorEmail);
      setEmailError(!ok);
      // Don't mirror an invalid email to storage; keep name + comment.
      persist({ author_email: ok ? authorEmail.trim() : "" });
      flash();
    };

    const onEmailChange = (e) => {
      setAuthorEmail(e.target.value);
      if (emailError && emailOk(e.target.value)) setEmailError(false);
    };

    let flashT;
    const flash = () => {
      setSaved(true);
      clearTimeout(flashT);
      flashT = setTimeout(() => setSaved(false), 1600);
    };

    return (
      <aside className="wp-react ui" aria-label={`Reactions for: ${sectionTitle}`}>
        <div className="wp-react-row">
          <span className="wp-react-prompt">How does this land?</span>
          <div className="wp-react-opts" role="group" aria-label="Reaction">
            {OPTIONS.map((o) => (
              <button
                key={o.id}
                type="button"
                className={"wp-react-btn" + (choice === o.id ? " is-active is-" + o.id : "")}
                aria-pressed={choice === o.id}
                title={o.hint}
                onClick={() => pick(o.id)}
              >
                <i data-lucide={o.icon} aria-hidden="true"></i>
                <span>{o.label}</span>
              </button>
            ))}
          </div>
          {!open && (
            <button type="button" className="wp-react-addlink" onClick={() => setOpen(true)}>
              <i data-lucide="message-square-plus" aria-hidden="true"></i>
              <span>Add a thought</span>
            </button>
          )}
        </div>

        {open && (
          <div className="wp-react-commentbox">
            <textarea
              className="wp-react-textarea"
              placeholder="Optional — what landed, or what you'd push back on…"
              value={comment}
              rows={2}
              onChange={(e) => setComment(e.target.value)}
              onBlur={commitComment}
              aria-label="Add a thought"
            ></textarea>

            <div className="wp-react-identity">
              <div className="wp-react-field">
                <input
                  type="text"
                  className="wp-react-input"
                  placeholder="Your name (optional)"
                  value={authorName}
                  onChange={(e) => setAuthorName(e.target.value)}
                  onBlur={commitComment}
                  aria-label="Your name (optional)"
                />
              </div>
              <div className={"wp-react-field" + (emailError ? " has-error" : "")}>
                <input
                  type="email"
                  className="wp-react-input"
                  placeholder="Email for a reply (optional)"
                  value={authorEmail}
                  onChange={onEmailChange}
                  onBlur={commitComment}
                  aria-label="Email for a reply (optional)"
                  aria-invalid={emailError}
                  autoComplete="email"
                />
                {emailError ? (
                  <span className="wp-react-err">Enter a valid email, or leave it blank.</span>
                ) : (
                  <span className="wp-react-hint">Only used to reply to this comment. Never marketed to.</span>
                )}
              </div>
            </div>

            <div className="wp-react-commentfoot">
              <span className={"wp-react-saved" + (saved ? " is-on" : "")}>
                <i data-lucide="check" aria-hidden="true"></i> Saved
              </span>
              <button type="button" className="wp-react-savebtn" onClick={commitComment}>Save</button>
            </div>
          </div>
        )}
      </aside>
    );
  }

  window.SectionReaction = SectionReaction;
})();
