// Create Project (search-first dedup → form) + Upload Artifact metadata modal

const CreateProjectModal = ({ open, onClose, onCreated, tier = "execution" }) => {
  const [stage, setStage] = React.useState("search"); // search | match | form | success
  const [client, setClient] = React.useState("");
  const [matched, setMatched] = React.useState(null);
  const [suggestions, setSuggestions] = React.useState([]);
  const [form, setForm] = React.useState({
    client: "", clientType: "", vertical: "", engagement: "", months: "", budget: "", client_details: ""
  });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setStage("search"); setClient(""); setMatched(null); setSuggestions([]);
      setForm({ client: "", clientType: "", vertical: "", engagement: "", months: "", budget: "", client_details: "" });
      setErrors({});
    }
  }, [open]);

  // Live search suggestions from backend
  React.useEffect(() => {
    if (!client.trim() || client.length < 1) { setSuggestions([]); return; }
    const t = setTimeout(() => {
      PrimaAPI.listProjects(client.trim())
        .then(results => setSuggestions((results || []).slice(0, 4)))
        .catch(() => setSuggestions([]));
    }, 250);
    return () => clearTimeout(t);
  }, [client]);

  const checkMatch = async () => {
    const q = client.trim().toLowerCase();
    if (!q) return;
    setLoading(true);
    try {
      const results = await PrimaAPI.listProjects(q);
      const exact = (results || []).find(p => p.client_name.toLowerCase() === q);
      if (exact) { setMatched(exact); setStage("match"); }
      else { setForm(f => ({ ...f, client })); setStage("form"); }
    } catch (e) {
      // If backend unavailable, proceed to form
      setForm(f => ({ ...f, client })); setStage("form");
    } finally {
      setLoading(false);
    }
  };

  const validate = () => {
    const e = {};
    if (!form.client.trim()) e.client = "Required.";
    if (!form.clientType) e.clientType = "Required.";
    if (!form.vertical) e.vertical = "Required.";
    if (!form.engagement) e.engagement = "Required.";
    if (!form.months || isNaN(+form.months) || +form.months < 1 || +form.months > 60) e.months = "Months must be between 1 and 60.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async () => {
    if (!validate()) return;
    setLoading(true);
    setErrors({});
    try {
      const resp = await PrimaAPI.createProject({
        client_name: form.client,
        client_type: form.clientType,
        vertical: form.vertical,
        engagement: form.engagement,
        months: parseInt(form.months, 10),
        budget: form.budget || undefined,
        client_details: form.client_details || "",
      });
      
      if (resp.message && resp.message.includes("already exists")) {
        // Leadership auto-joined case
        setMatched(resp);
        setStage("success");
        setTimeout(() => { onCreated(resp); onClose(); }, 1500);
      } else {
        setStage("success");
        setTimeout(() => { onCreated(resp); onClose(); }, 1100);
      }
    } catch (e) {
      if (e.status === 409) {
        // Management join request sent case
        setJoinSent(true);
        setStage("match"); // Go back to match stage to show the "Request Sent" message
        setErrors({ api: e.message });
      } else {
        setErrors({ api: e.message || "Failed to create project." });
      }
    } finally {
      setLoading(false);
    }
  };

  const [joinSent, setJoinSent] = React.useState(false);
  const joinExisting = async () => {
    if (!matched) return;
    setLoading(true);
    try {
      const resp = await PrimaAPI.joinProject(matched.id);
      if (resp && resp.status === "approved") {
        // Leadership auto-approve: enter project immediately
        onCreated(matched);
        onClose();
      } else {
        setJoinSent(true);
      }
    } catch (e) {
      setErrors({ api: e.message || "Failed to request access." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} size="lg"
           title={stage === "success" ? "Project created" : "Create project"}
           sub={stage === "search" ? "Search-first to prevent duplicates."
              : stage === "match" ? "We found something similar."
              : stage === "form" ? "Tell us about the engagement."
              : "Folders are being generated."}
           footer={
             stage === "search" ? (
               <>
                 <button className="btn ghost" onClick={onClose}>Cancel</button>
                 <button className="btn primary" disabled={!client.trim() || loading} onClick={checkMatch}>
                   {loading ? "Searching…" : <><span>Continue</span> <Icon name="chevron-right" size={14} /></>}
                 </button>
               </>
             ) : stage === "match" ? (
               <>
                 <button className="btn ghost" onClick={() => { setStage("search"); setJoinSent(false); }}>Back</button>
                 {joinSent ? (
                   <button className="btn" disabled style={{ color: "var(--ok, #16a34a)" }}>
                     <Icon name="check" size={13} /> Request sent — awaiting approval
                   </button>
                 ) : (
                  tier !== "execution" ? (
                    <button className="btn accent" onClick={joinExisting} disabled={loading}>
                      <Icon name="users" size={13} /> {loading ? "Requesting…" : "Request to join"}
                    </button>
                  ) : (
                    <div style={{ fontSize: 12, color: "var(--fg-subtle)", padding: "4px 0" }}>
                      Ask the project owner to invite you.
                    </div>
                  )
                 )}
               </>
             ) : stage === "form" ? (
               <>
                 <button className="btn ghost" onClick={() => setStage("search")}>Back</button>
                 <button className="btn primary" onClick={submit} disabled={loading}>
                   {loading ? "Creating…" : <><Icon name="check" size={14} /> Create project</>}
                 </button>
               </>
             ) : null
           }>

      {stage === "search" && (
        <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Field label="Search by project name" required hint="We'll check for existing projects — duplicates are blocked.">
            <div style={{ position: "relative" }}>
              <TextInput value={client} onChange={e => setClient(e.target.value)}
                         placeholder="Start typing the project name…" autoFocus
                         onKeyDown={(e) => { if (e.key === "Enter" && client.trim()) checkMatch(); }} />
              {suggestions.length > 0 && (
                <div className="chip-suggest-list" style={{ marginTop: 4 }}>
                  {suggestions.map(p => (
                    <button key={p.id} onMouseDown={(e) => { e.preventDefault(); setClient(p.client_name); setMatched(p); setStage("match"); }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <span><strong>{p.client_name}</strong> · <span style={{ color: "var(--fg-subtle)" }}>{p.vertical}</span></span>
                        <span className="tag" style={{ marginLeft: 8 }}>{p.code}</span>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </Field>
          <div style={{ display: "flex", gap: 8, alignItems: "center", color: "var(--fg-subtle)", fontSize: 12 }}>
            <Icon name="info" size={12} /> Already exists? You'll be able to request access to contribute.
          </div>
        </div>
      )}

      {stage === "match" && matched && (
        <div className="modal-body">
          {errors.api && <div style={{ marginBottom: 12, color: "var(--err, #dc2626)", fontSize: 13 }}>{errors.api}</div>}
          <div className="card" style={{ background: "var(--bg-sunk)" }}>
            <div className="card-body">
              <div className="eyebrow"><Icon name="alert" size={11} /> This project already exists</div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em" }}>{matched.client_name}</div>
              <div style={{ color: "var(--fg-muted)", fontSize: 13, margin: "4px 0 12px" }}>
                {matched.client_type} · {matched.vertical}
              </div>
              <div style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.55 }}>{matched.description || "—"}</div>
              <div style={{ marginTop: 14, padding: "10px 0", borderTop: "1px dashed var(--hairline)", display: "flex", gap: 16, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-subtle)" }}>
                <span>{matched.code}</span>
                <span>{matched.engagement}</span>
                <span className={"tag " + (matched.status === "active" ? "ok" : "")}>{matched.status}</span>
              </div>
            </div>
          </div>
          <p style={{ fontSize: 13, color: "var(--fg-muted)", marginTop: 14 }}>
            Duplicate projects are <strong style={{ color: "var(--fg)" }}>blocked</strong>. Request to join — the project Owner or any Tier 1 (VP+) user can approve. Once approved, this project appears in your workspace with upload rights.
          </p>
        </div>
      )}

      {stage === "form" && (
        <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {errors.api && <div style={{ padding: "10px 14px", background: "var(--err-soft, #fef2f2)", color: "var(--err, #dc2626)", borderRadius: 6, fontSize: 13 }}>{errors.api}</div>}
          <div className="grid-2">
            <Field label="Project name" required error={errors.client}>
              <TextInput value={form.client} onChange={e => setForm({ ...form, client: e.target.value })} error={errors.client} />
            </Field>
            <Field label="Client type" required error={errors.clientType}>
              <Select value={form.clientType} onChange={v => setForm({ ...form, clientType: v })} options={TAXONOMY.clientTypes} error={errors.clientType} />
            </Field>
          </div>
          <Field label="Client details" optional hint="Background on the client — department, key contacts, brief context.">
            <textarea
              value={form.client_details}
              onChange={e => setForm({ ...form, client_details: e.target.value })}
              placeholder="e.g. Urban Development Ministry, Maharashtra — point of contact: Mr. Sharma (Joint Secretary)"
              rows={3}
              style={{ width: "100%", resize: "vertical", padding: "8px 10px", border: "1px solid var(--border)", borderRadius: "var(--r-input)", background: "var(--bg)", color: "var(--fg)", fontFamily: "var(--font-ui)", fontSize: 13, lineHeight: 1.5 }}
            />
          </Field>
          <div className="grid-2">
            <Field label="Consulting vertical" required error={errors.vertical}>
              <Select value={form.vertical} onChange={v => setForm({ ...form, vertical: v })} options={TAXONOMY.verticals} error={errors.vertical} />
            </Field>
            <Field label="Engagement type" required error={errors.engagement}>
              <Select value={form.engagement} onChange={v => setForm({ ...form, engagement: v })} options={TAXONOMY.engagements} error={errors.engagement} />
            </Field>
          </div>
          <div className="grid-2">
            <Field label="Timeline (months)" required error={errors.months}>
              <TextInput type="number" min="1" max="60" value={form.months} onChange={e => setForm({ ...form, months: e.target.value })} placeholder="6" error={errors.months} />
            </Field>
            <Field label="Budget range" optional>
              <Select value={form.budget} onChange={v => setForm({ ...form, budget: v })} options={TAXONOMY.budgets} placeholder="Optional…" />
            </Field>
          </div>
          <div style={{ background: "var(--bg-sunk)", padding: 12, borderRadius: "var(--r-input)", fontSize: 12, color: "var(--fg-muted)", display: "flex", gap: 10, alignItems: "flex-start" }}>
            <Icon name="info" size={13} style={{ marginTop: 1, color: "var(--accent-deep)" }} />
            <span>On creation, we auto-generate the six standard folders (01_Proposal_BD → 06_Financial_Docs) and tag the project for the Prima Research pipeline.</span>
          </div>
        </div>
      )}

      {stage === "success" && (
        <div className="modal-body" style={{ textAlign: "center", padding: "32px 24px" }}>
          <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent-deep)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
            <Icon name="check" size={28} stroke={2} />
          </div>
          <h3 style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500, margin: "0 0 6px" }}>Project created</h3>
          <p style={{ color: "var(--fg-muted)", margin: 0 }}>Generating folder structure…</p>
        </div>
      )}
    </Modal>
  );
};

// ─── Upload artifact metadata ───
const UploadArtifactModal = ({ open, onClose, onSaved, defaultFolderId, openProject }) => {
  const [stage, setStage] = React.useState("drop"); // drop | meta | uploading | done
  const [file, setFile] = React.useState(null);
  const [folderId, setFolderId] = React.useState(defaultFolderId || "01");
  const [meta, setMeta] = React.useState({
    fileType: "PDF", docType: "", conf: "internal",
    approvedBy: "", submittedTo: "",
    reusable: false, bestInClass: false, managerApproved: false
  });
  const [errors, setErrors] = React.useState({});
  const [uploading, setUploading] = React.useState(false);
  const fileInputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setStage("drop"); setFile(null);
      setFolderId(defaultFolderId || "01");
      setMeta({ fileType: "PDF", docType: "", conf: "internal", approvedBy: "", submittedTo: "", reusable: false, bestInClass: false, managerApproved: false });
      setErrors({});
    }
  }, [open, defaultFolderId]);

  const handleFileSelect = (selectedFile) => {
    if (!selectedFile) return;
    setFile(selectedFile);
    // Auto-detect file type from extension
    const ext = selectedFile.name.split(".").pop().toUpperCase();
    const knownTypes = { PDF: "PDF", DOC: "DOCX", DOCX: "DOCX", PPT: "PPTX", PPTX: "PPTX", XLS: "XLSX", XLSX: "XLSX", MP4: "MP4" };
    setMeta(m => ({ ...m, fileType: knownTypes[ext] || "PDF" }));
    setStage("meta");
  };

  const handleSave = async () => {
    if (!meta.docType) { setErrors({ docType: "Required." }); return; }
    if (!openProject) { setErrors({ api: "No project selected. Open a project first." }); return; }
    setErrors({});
    setUploading(true);
    try {
      let gcsPath = null;
      if (file) {
        const uploadResp = await PrimaAPI.uploadFile(openProject.id, folderId, file);
        gcsPath = uploadResp.gcs_path;
      }

      await PrimaAPI.saveArtifact({
        project_id: openProject.id,
        folder_id: folderId,
        file_name: file ? file.name : "unknown",
        file_type: meta.fileType,
        doc_type: meta.docType,
        confidentiality: meta.conf === "confidential" ? "client_confidential" : meta.conf,
        gcs_path: gcsPath || undefined,
        approved_by: meta.approvedBy,
        submitted_to: meta.submittedTo,
        reusable: meta.reusable,
        best_in_class: meta.bestInClass,
        manager_approved: meta.managerApproved,
      });

      onSaved(file ? file.name : "file");
      onClose();
    } catch (e) {
      setErrors({ api: e.message || "Upload failed." });
    } finally {
      setUploading(false);
    }
  };

  const selectedFolder = FOLDERS.find(f => f.id === folderId) || FOLDERS[0];

  return (
    <Modal open={open} onClose={onClose} size="lg"
           title={stage === "drop" ? "Upload artifact" : "Capture metadata"}
           sub={stage === "drop"
             ? `Destination: ${selectedFolder.name}`
             : "These tags drive Prima Research retrieval. Be precise."}
           footer={stage === "drop" ? (
             <>
               <button className="btn ghost" onClick={onClose}>Cancel</button>
               <button className="btn primary" disabled={!file} onClick={() => file && setStage("meta")}>
                 Continue <Icon name="chevron-right" size={14} />
               </button>
             </>
           ) : (
             <>
               <button className="btn ghost" onClick={() => setStage("drop")} disabled={uploading}>Back</button>
               <button className="btn accent" onClick={handleSave} disabled={uploading}>
                 {uploading ? "Uploading…" : <><Icon name="check" size={14} /> Save &amp; ingest</>}
               </button>
             </>
           )}>

      {/* Hidden file input */}
      <input
        ref={fileInputRef}
        type="file"
        style={{ display: "none" }}
        accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.mp4,.jpg,.jpeg,.png,.gif"
        onChange={e => handleFileSelect(e.target.files[0])}
      />

      {stage === "drop" ? (
        <div className="modal-body">
          <Field label="Destination folder" required hint="Pick where this artifact lives in the project hierarchy.">
            <div className="folder-picker">
              {FOLDERS.map(f => (
                <button key={f.id} type="button"
                        className="folder-pick"
                        data-active={folderId === f.id}
                        onClick={() => setFolderId(f.id)}>
                  <span className="num">{f.id}</span>
                  <span className="lbl">
                    <span className="nm">{f.name.replace(/^\d+_/, "")}</span>
                    <span className="ds">{f.tip}</span>
                  </span>
                  {folderId === f.id && <Icon name="check" size={13} />}
                </button>
              ))}
            </div>
          </Field>
          <div className="dropzone" style={{ marginTop: 14 }}
               onDragOver={(e) => { e.preventDefault(); e.currentTarget.dataset.over = "true"; }}
               onDragLeave={(e) => { e.currentTarget.dataset.over = "false"; }}
               onDrop={(e) => { e.preventDefault(); e.currentTarget.dataset.over = "false"; handleFileSelect(e.dataTransfer.files[0]); }}
               onClick={() => fileInputRef.current && fileInputRef.current.click()}>
            <Icon name="upload" size={28} />
            <div className="big" style={{ marginTop: 10 }}>Drop files here or click to browse</div>
            <div>PDF · DOCX · PPTX · XLSX · MP4 · Image — up to 2 GB each</div>
            {file && <div style={{ marginTop: 8, color: "var(--accent-deep)", fontWeight: 500 }}>{file.name} selected</div>}
          </div>
          <div style={{ display: "flex", gap: 10, marginTop: 14, padding: "10px 12px", background: "var(--bg-sunk)", borderRadius: "var(--r-input)", fontSize: 12, color: "var(--fg-muted)", alignItems: "flex-start" }}>
            <Icon name="info" size={13} style={{ color: "var(--accent-deep)", marginTop: 1 }} />
            <span>After upload, you'll capture metadata (type, confidentiality, governance). Files won't be ingested into Prima Research until tagged.</span>
          </div>
        </div>
      ) : (
        <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {errors.api && (
            <div style={{ padding: "10px 14px", background: "var(--err-soft, #fef2f2)", color: "var(--err, #dc2626)", borderRadius: 6, fontSize: 13 }}>{errors.api}</div>
          )}
          {file && (
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", background: "var(--bg-sunk)", borderRadius: "var(--r-input)" }}>
              <div className={"file-icon " + file.name.split(".").pop().toLowerCase()}>{file.name.split(".").pop().toUpperCase()}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 500 }}>{file.name}</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-subtle)" }}>
                  {(file.size / 1024 / 1024).toFixed(1)} MB
                </div>
              </div>
              <span className="tag ok"><Icon name="check" size={10} /> Ready</span>
            </div>
          )}

          <div className="grid-2">
            <Field label="File type">
              <Select value={meta.fileType} onChange={v => setMeta({ ...meta, fileType: v })} options={TAXONOMY.fileTypes} />
            </Field>
            <Field label="Document type" required error={errors.docType}>
              <Select value={meta.docType} onChange={v => setMeta({ ...meta, docType: v })} options={TAXONOMY.docTypes} error={errors.docType} />
            </Field>
          </div>

          <Field label="Confidentiality" required hint="Defines downstream access in the RAG pipeline.">
            <div className="conf-grid">
              {TAXONOMY.confidentiality.map(c => (
                <button key={c.id} type="button"
                        data-active={meta.conf === c.id}
                        onClick={() => setMeta({ ...meta, conf: c.id })}>
                  <span className="lbl">
                    <span className="swatch" style={{ background: { public: "var(--ok)", internal: "var(--info)", restricted: "var(--warn)", confidential: "var(--err)" }[c.id] }} />
                    {c.label}
                  </span>
                  <span className="desc">{c.desc}</span>
                </button>
              ))}
            </div>
          </Field>

          <div className="grid-2">
            <Field label="Approved by" optional hint="Project lead / partner.">
              <TextInput value={meta.approvedBy} onChange={e => setMeta({ ...meta, approvedBy: e.target.value })} placeholder="e.g. M. Aravind" />
            </Field>
            <Field label="Submitted to" optional hint="Stakeholder at the client end.">
              <TextInput value={meta.submittedTo} onChange={e => setMeta({ ...meta, submittedTo: e.target.value })} placeholder="e.g. Smt. K. Iyer" />
            </Field>
          </div>

          <div>
            <div className="field-label">Governance flags</div>
            <div style={{ display: "flex", gap: 8, marginTop: 6 }}>
              {[
                { k: "reusable", l: "Reusable" },
                { k: "bestInClass", l: "Best-in-Class" },
                { k: "managerApproved", l: "Manager Approved" },
              ].map(g => (
                <button key={g.k} type="button"
                        className="btn sm"
                        style={meta[g.k] ? { background: "var(--accent-soft)", color: "var(--accent-fg)", borderColor: "var(--accent-deep)" } : {}}
                        onClick={() => setMeta({ ...meta, [g.k]: !meta[g.k] })}>
                  {meta[g.k] && <Icon name="check" size={11} />} {g.l}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
};

// Command palette (⌘K)
const CommandPalette = ({ open, onClose, onNav, onCreate, onUpload }) => {
  const [q, setQ] = React.useState("");
  React.useEffect(() => { if (open) setQ(""); }, [open]);
  const cmds = [
    { id: "ws", label: "Go to Project Workspace", hint: "G W", action: () => onNav("workspace"), icon: "folder" },
    { id: "rh", label: "Go to Research Hub", hint: "G R", action: () => onNav("research"), icon: "book" },
    { id: "tl", label: "Go to Thought Leadership", hint: "G T", action: () => onNav("thought"), icon: "mic" },
    { id: "lb", label: "Go to Leaderboard", hint: "G L", action: () => onNav("leaderboard"), icon: "trophy" },
    { id: "pr", label: "Update profile", hint: "G P", action: () => onNav("profile"), icon: "user" },
    { id: "np", label: "Create new project", hint: "C", action: onCreate, icon: "plus" },
    { id: "up", label: "Upload artifact", hint: "U", action: onUpload, icon: "upload" },
  ];
  const filtered = q.trim() ? cmds.filter(c => c.label.toLowerCase().includes(q.toLowerCase())) : cmds;
  if (!open) return null;
  return (
    <div className="modal-backdrop" onMouseDown={(e) => { if (e.target.classList.contains("modal-backdrop")) onClose(); }}>
      <div className="modal" style={{ maxWidth: 520, padding: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 18px", borderBottom: "1px solid var(--hairline)" }}>
          <Icon name="search" size={16} />
          <input autoFocus value={q} onChange={e => setQ(e.target.value)}
                 placeholder="Type a command or search…"
                 style={{ flex: 1, border: 0, background: "transparent", outline: "none", fontSize: 15, color: "var(--fg)" }} />
          <kbd style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-subtle)" }}>esc</kbd>
        </div>
        <div style={{ maxHeight: 360, overflow: "auto", padding: 6 }}>
          {filtered.map(c => (
            <button key={c.id}
                    onClick={() => { c.action(); onClose(); }}
                    style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", padding: "10px 12px", border: 0, background: "transparent", borderRadius: 4, color: "var(--fg)", textAlign: "left", fontSize: 13.5 }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-tint)"}
                    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <Icon name={c.icon} size={15} />
              <span style={{ flex: 1 }}>{c.label}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-subtle)" }}>{c.hint}</span>
            </button>
          ))}
          {filtered.length === 0 && (
            <div style={{ padding: 24, textAlign: "center", color: "var(--fg-subtle)", fontSize: 13 }}>No matches.</div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { CreateProjectModal, UploadArtifactModal, CommandPalette });
