// epic-modal.jsx — "New epic" modal (title + color + owner)

const EPIC_COLORS = [
  { id: "purple", hex: "#a25ddc", label: "Purple" },
  { id: "blue",   hex: "#0073ea", label: "Blue"   },
  { id: "teal",   hex: "#0086c0", label: "Teal"   },
  { id: "green",  hex: "#00c875", label: "Green"  },
  { id: "yellow", hex: "#fdab3d", label: "Yellow" },
  { id: "red",    hex: "#e2445c", label: "Red"    },
  { id: "pink",   hex: "#ff5ac4", label: "Pink"   },
  { id: "indigo", hex: "#5559df", label: "Indigo" },
  { id: "gray",   hex: "#676879", label: "Gray"   },
];

function NewEpicModal({ open, onClose, onCreate, projects = [], defaultProjectId, defaultOwnerId, people = [] }) {
  const [title, setTitle] = React.useState("");
  const [color, setColor] = React.useState(EPIC_COLORS[0].hex);
  const [projectId, setProjectId] = React.useState(defaultProjectId || (projects[0] && projects[0].id) || "");
  const [ownerId, setOwnerId]     = React.useState(defaultOwnerId || "");
  const [busy, setBusy]           = React.useState(false);
  const [err, setErr]             = React.useState("");

  const titleRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    setTitle("");
    setColor(EPIC_COLORS[0].hex);
    setProjectId(defaultProjectId || (projects[0] && projects[0].id) || "");
    setOwnerId(defaultOwnerId || "");
    setBusy(false);
    setErr("");
    setTimeout(() => titleRef.current?.focus(), 50);
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape" && !busy) onClose();
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") submit();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, title, color, projectId, ownerId, busy]);

  async function submit() {
    const t = title.trim();
    if (!t || !projectId || busy) return;
    setBusy(true);
    setErr("");
    try {
      await onCreate({ title: t, color, project_id: projectId, owner_id: ownerId || null });
      onClose();
    } catch (e) {
      setErr(e?.message || "Could not create epic");
      setBusy(false);
    }
  }

  if (!open) return null;

  const activePeople = (people && people.length ? people : (typeof PEOPLE !== "undefined" ? PEOPLE : []))
    .filter(p => !p.status || p.status === "active");
  const projectList = projects && projects.length
    ? projects
    : (typeof PROJECTS !== "undefined" ? PROJECTS : []);

  return ReactDOM.createPortal(
    <div className="modal-backdrop" onMouseDown={() => !busy && onClose()}>
      <div className="modal nt-modal" onMouseDown={e => e.stopPropagation()} style={{ width: 540 }}>
        <div className="modal-header">
          <div style={{ flex: 1 }}>
            <div className="nt-breadcrumb"><Icons.Folder size={11}/> Epic → New</div>
            <div className="modal-title">Create a new epic</div>
          </div>
          <button className="modal-close" onClick={() => !busy && onClose()}><Icons.Close size={16}/></button>
        </div>

        <div className="modal-body">
          <div className="ms-grid">
            <div className="ms-row">
              <label className="ms-label">Title</label>
              <input className="ms-input nt-name"
                     ref={titleRef}
                     placeholder="e.g. Onboarding redesign"
                     value={title} onChange={e => setTitle(e.target.value)}
                     onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); } }}/>
            </div>

            {projectList.length > 1 && (
              <div className="ms-row">
                <label className="ms-label">Project</label>
                <select className="ms-input" value={projectId} onChange={e => setProjectId(e.target.value)}>
                  {projectList.map(p => <option key={p.id} value={p.id}>{p.name || p.title || p.id}</option>)}
                </select>
              </div>
            )}

            <div className="ms-row">
              <label className="ms-label">Color</label>
              <div className="nt-prio-row" style={{ flexWrap: "wrap" }}>
                {EPIC_COLORS.map(c => (
                  <button key={c.id}
                          className="nt-prio-chip"
                          onClick={() => setColor(c.hex)}
                          title={c.label}
                          style={{
                            background: color === c.hex ? c.hex : "#fff",
                            color: color === c.hex ? "#fff" : c.hex,
                            borderColor: c.hex,
                            fontWeight: color === c.hex ? 700 : 500,
                            minWidth: 88,
                          }}>
                    <span style={{
                      display: "inline-block", width: 10, height: 10, borderRadius: 3,
                      background: c.hex, marginRight: 6, verticalAlign: "middle",
                      border: color === c.hex ? "1px solid rgba(255,255,255,.6)" : "none",
                    }}/>
                    {c.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="ms-row">
              <label className="ms-label">Owner <span className="ms-optional">(optional)</span></label>
              <select className="ms-input" value={ownerId} onChange={e => setOwnerId(e.target.value)}>
                <option value="">No owner</option>
                {activePeople.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </div>

            {err && (
              <div className="ms-row" style={{ color: "#c0223a", fontSize: 12 }}>{err}</div>
            )}
          </div>
        </div>

        <div className="modal-footer">
          <div style={{ flex: 1, color: "var(--ink-muted)", fontSize: 11 }}>
            <kbd className="nt-kbd">⌘</kbd><kbd className="nt-kbd">↵</kbd> to create
          </div>
          <button className="btn" onClick={() => !busy && onClose()} disabled={busy}>Cancel</button>
          <button className="btn btn-primary" disabled={!title.trim() || !projectId || busy} onClick={submit}>
            {busy ? <>Creating…</> : <><Icons.Plus size={13}/> Create epic</>}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}

Object.assign(window, { NewEpicModal, EPIC_COLORS });
