/* Edit drawer — same chrome as capture, populated with the entry.
 *
 * Audio + transcript are read-only here; only the body summary, member
 * tags, follow-up flag, and tag chip can be edited. This matches the
 * spec's intent: the transcript is the source-of-truth, and the
 * body summary is the displayed surface.
 */
(function () {
  const { useState, useEffect } = React;
  const {
    Drawer,
    Button,
    TextArea,
    MemberPicker,
    Pill,
    Icons,
    members,
    entries,
    showToast,
    tokens,
  } = window.CC;

  const NOTE_TAGS = [
    { value: null, label: "None" },
    { value: "decision", label: "Decision" },
    { value: "observation", label: "Observation" },
    { value: "idea", label: "Idea" },
    { value: "fyi", label: "FYI" },
    { value: "win", label: "Win" },
  ];

  function EditEntry({ entry, onClose }) {
    const [body, setBody] = useState(entry?.body || "");
    const [followup, setFollowup] = useState(Boolean(entry?.needs_followup));
    const [tag, setTag] = useState(entry?.tag || null);
    const [memberObjs, setMemberObjs] = useState(() =>
      (entry?.members || []).map(members.byId).filter(Boolean)
    );
    const [saving, setSaving] = useState(false);

    useEffect(() => {
      if (!entry) return;
      setBody(entry.body || "");
      setFollowup(Boolean(entry.needs_followup));
      setTag(entry.tag || null);
      setMemberObjs((entry.members || []).map(members.byId).filter(Boolean));
    }, [entry]);

    async function save() {
      if (!entry) return;
      setSaving(true);
      try {
        await entries.update(entry.id, {
          body: body.trim() || entry.body,
          needs_followup: followup,
          tag,
          members: memberObjs.map((m) => m.row_id),
        });
        showToast("Saved.");
        onClose();
      } catch (e) {
        showToast("Couldn’t save.");
      } finally {
        setSaving(false);
      }
    }

    if (!entry) return null;

    return (
      <Drawer
        open={Boolean(entry)}
        onClose={onClose}
        title="Edit entry"
        footer={
          <Button fullWidth size="lg" onClick={save} loading={saving}>
            Save
          </Button>
        }
      >
        <div style={{ display: "grid", gap: 16 }}>
          <TextArea
            label="Summary"
            value={body}
            onChange={setBody}
            rows={3}
            maxRows={10}
          />

          <MemberPicker
            label={entry.type === "member" ? "Member" : "Tagged members"}
            multi={entry.type !== "member"}
            value={
              entry.type === "member"
                ? memberObjs[0] || null
                : memberObjs
            }
            onChange={(v) => {
              if (Array.isArray(v)) setMemberObjs(v);
              else setMemberObjs(v ? [v] : []);
            }}
          />

          {entry.type === "note" && (
            <div>
              <div className="cc-toggle-row__label">Tag</div>
              <div className="cc-tag-row">
                {NOTE_TAGS.map((t) => (
                  <button
                    key={t.label}
                    type="button"
                    onClick={() => setTag(t.value)}
                    className={`cc-tag ${tag === t.value ? "is-active" : ""}`}
                  >
                    {t.label}
                  </button>
                ))}
              </div>
            </div>
          )}

          {entry.type === "member" && (
            <label className="cc-toggle-row">
              <input
                type="checkbox"
                checked={followup}
                onChange={(e) => setFollowup(e.target.checked)}
              />
              <span>Needs follow-up</span>
              <span
                style={{
                  color: tokens.colors.textDim,
                  fontSize: 13,
                  marginLeft: "auto",
                }}
              >
                appears in Attention
              </span>
            </label>
          )}

          {entry.transcript && entry.transcript !== entry.body && (
            <details className="cc-edit-readonly">
              <summary>Original transcript (read-only)</summary>
              <pre>{entry.transcript}</pre>
            </details>
          )}
        </div>
      </Drawer>
    );
  }

  window.CC = window.CC || {};
  window.CC.EditEntry = EditEntry;
})();
