/* email-composer.jsx
 * EmailComposer modal — appears on every stage-move action.
 * Requires: email-store.jsx, app.jsx (I, Avatar, Pill globals).
 */

/* ── Local icon helpers (not in app.jsx I object) ───────────────────────── */
const IcMail = (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m2 7 10 7 10-7"/></svg>);
const IcArrowRight = (p) => (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M12 5l7 7-7 7"/></svg>);

/* Stage-based hint copy */
const STAGE_HINTS = {
  intro_screening: "A short, warm note to schedule your 30-minute intro call.",
  hiring_manager:  "Let them know they've impressed the team and what to expect next.",
  technical_test:  "Set expectations clearly — effort required and timeline for the exercise.",
  offer:           "Keep it warm and personal. This is a memorable moment for them.",
  hired:           "Celebrate! Make them feel genuinely welcome before day one.",
  rejected:        "Be respectful and specific. Leave the door open for future roles.",
};

/* ── EmailComposer ───────────────────────────────────────────────────────── */

function EmailComposer({
  candidateName,
  candidateEmail,
  candidateHue,
  postingTitle,
  fromStageId,
  fromStageLabel,
  toStageId,
  toStageLabel,
  toStageAccent,
  fromStageAccent,
  onSendAndMove,
  onDiscardAndMove,
  onCancel,
}) {
  const { useState, useEffect, useRef, useCallback } = React;

  /* Load prefilled template */
  const [subject, setSubject] = useState("");
  const [body,    setBody]    = useState("");
  const [loaded,  setLoaded]  = useState(false);
  const bodyRef = useRef(null);

  useEffect(() => {
    const firstName = (candidateName || "").split(" ")[0] || "there";
    const tpl = getTemplateForStage(toStageId);
    if (tpl) {
      const rendered = renderEmailTemplate(tpl, {
        contact: { firstName, lastName: (candidateName || "").split(" ").slice(1).join(" ") },
        posting: { title: postingTitle || "", location: "" },
        stage:   { label: toStageLabel || "" },
      });
      setSubject(rendered.subject);
      setBody(rendered.body);
    }
    setLoaded(true);
  }, [toStageId, candidateName, postingTitle, toStageLabel]);

  /* Auto-grow textarea */
  useEffect(() => {
    if (bodyRef.current) {
      bodyRef.current.style.height = "auto";
      bodyRef.current.style.height = bodyRef.current.scrollHeight + "px";
    }
  }, [body]);

  /* Escape key */
  useEffect(() => {
    const fn = (e) => { if (e.key === "Escape") onCancel && onCancel(); };
    document.addEventListener("keydown", fn);
    return () => document.removeEventListener("keydown", fn);
  }, [onCancel]);

  const handleSend = useCallback(() => {
    onSendAndMove && onSendAndMove({
      to:      candidateEmail,
      subject,
      body,
      sentAt:  new Date().toISOString(),
    });
  }, [candidateEmail, subject, body, onSendAndMove]);

  const hint = STAGE_HINTS[toStageId] || "Send a note to keep the candidate informed.";

  return (
    <div className="ec-scrim" onClick={(e) => { if (e.target === e.currentTarget) onCancel && onCancel(); }}>
      <div className="ec-shell" role="dialog" aria-modal="true" aria-label="Email composer">

        {/* ── Header ── */}
        <div className="ec-header">
          <div className="ec-header-eyebrow">
            <span className="ec-eyebrow-icon"><IcArrowRight width="12" height="12" /></span>
            Moving to · <strong>{toStageLabel}</strong>
          </div>
          <div className="ec-header-row">
            <div className="ec-header-title-group">
              <h2 className="ec-title">Send {candidateName} an email?</h2>
              <p className="ec-hint">{hint}</p>
            </div>
            <button className="icon-btn ec-close" onClick={onCancel} aria-label="Close">
              <I.X width="18" height="18" />
            </button>
          </div>

          {/* Stage flow chip */}
          <div className="ec-stage-flow">
            <span className="ec-stage-chip" style={{ background: fromStageAccent || "var(--neutral-20)", color: "var(--content-secondary)" }}>
              {fromStageLabel}
            </span>
            <IcArrowRight width="14" height="14" style={{ color: "var(--content-tertiary)", flexShrink: 0 }} />
            <span className="ec-stage-chip ec-stage-chip--to" style={{ background: toStageAccent || "var(--indigo-10)", color: "var(--content-primary)" }}>
              {toStageLabel}
            </span>
          </div>
        </div>

        {/* ── Meta rows ── */}
        <div className="ec-meta">
          <div className="ec-meta-row">
            <span className="ec-meta-label">From</span>
            <span className="ec-meta-value">{RECRUITER_NAME} &lt;{RECRUITER_EMAIL}&gt;</span>
          </div>
          <div className="ec-meta-row">
            <span className="ec-meta-label">To</span>
            <span className="ec-meta-value">
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <Avatar name={candidateName} size={18} tone={candidateHue || "auto"} />
                {candidateName}
                {candidateEmail && (
                  <span style={{ color: "var(--content-tertiary)", fontWeight: 400 }}>
                    &lt;{candidateEmail}&gt;
                  </span>
                )}
              </span>
            </span>
          </div>
          <div className="ec-meta-row">
            <span className="ec-meta-label">Re</span>
            <span className="ec-meta-value">{postingTitle || "—"}</span>
          </div>
        </div>

        {/* ── Compose area ── */}
        <div className="ec-compose">
          <div className="ec-field ec-field--subject">
            <label className="ec-field-label">Subject</label>
            <input
              className="ec-subject-input"
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Subject line…"
            />
          </div>
          <div className="ec-field ec-field--body">
            <label className="ec-field-label">Message</label>
            <textarea
              ref={bodyRef}
              className="ec-body-textarea"
              value={body}
              onChange={(e) => {
                setBody(e.target.value);
              }}
              placeholder="Your message…"
              rows={10}
            />
          </div>

          {/* Template note */}
          <div className="ec-template-note">
            <IcMail width="12" height="12" style={{ color: "var(--content-tertiary)", flexShrink: 0 }} />
            <span>
              Prefilled from the <em>{toStageLabel}</em> template.{" "}
              <a
                href="#settings"
                className="ec-template-link"
                onClick={(e) => {
                  /* Drive the hash navigation explicitly, then close the
                     composer. Relying on <a href>'s default action races
                     with React's re-render that unmounts this element. */
                  e.preventDefault();
                  window.location.hash = "settings";
                  if (onCancel) onCancel();
                }}
              >
                Manage templates →
              </a>
            </span>
          </div>
        </div>

        {/* ── Footer ── */}
        <div className="ec-footer">
          <button
            className="btn btn-outline btn-sm ec-discard-btn"
            onClick={() => onDiscardAndMove && onDiscardAndMove()}
          >
            Discard email &amp; move anyway
          </button>
          <div className="ec-footer-right">
            <button className="btn btn-outline btn-sm" onClick={onCancel}>
              Cancel
            </button>
            <button
              className="btn btn-brand btn-sm ec-send-btn"
              onClick={handleSend}
              disabled={!subject.trim() || !body.trim()}
            >
              <I.Send width="13" height="13" />
              Send &amp; move to {toStageLabel}
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}

window.EmailComposer = EmailComposer;
