// Research Hub + Thought Leadership (wired to PrimaAPI)

const ResearchHub = ({ showRbac }) => {
  const [cat, setCat] = React.useState("all");
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showAdd, setShowAdd] = React.useState(false);

  const loadItems = () => {
    setLoading(true);
    PrimaAPI.listResearch()
      .then(data => setItems(data || []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  };

  React.useEffect(() => { loadItems(); }, []);

  // Map API fields to display format
  const display = items.map(r => ({
    id: r.id,
    title: r.title,
    source: r.source,
    category: r.category,
    scope: r.geo_scope || [],
    industries: r.industry_tags || [],
    date: r.publish_date || "—",
    conf: r.confidentiality || "internal",
  }));

  const filtered = display.filter(r => cat === "all" || r.category === cat);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow"><Icon name="book" size={11} /> External intelligence</div>
          <h1 className="page-title">Research <em>Hub</em></h1>
          <p className="page-sub">Whitepapers, market scans, competitor benchmarks, and regulatory notes from external sources — tagged for downstream retrieval.</p>
        </div>
        <button className="btn primary" onClick={() => setShowAdd(true)}><Icon name="plus" size={14} /> Add research</button>
      </div>

      <div className="filter-rail">
        <div className="pill-group">
          {["all", ...TAXONOMY.researchCats].map(c => (
            <button key={c} data-active={cat === c} onClick={() => setCat(c)}>{c === "all" ? "All" : c}</button>
          ))}
        </div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-subtle)" }}>Sources:</span>
          {TAXONOMY.publishers.slice(0, 4).map(p => <span key={p} className="tag">{p}</span>)}
        </div>
      </div>

      {loading ? (
        <div className="empty" style={{ marginTop: 24 }}>
          <div style={{ color: "var(--fg-muted)", fontFamily: "var(--font-mono)", fontSize: 13 }}>Loading…</div>
        </div>
      ) : filtered.length === 0 ? (
        <div className="empty" style={{ marginTop: 24 }}>
          <div className="icon"><Icon name="book" size={20} /></div>
          <h3>No research items yet</h3>
          <p>Add external intelligence to build the firm's knowledge base.</p>
          <button className="btn primary" onClick={() => setShowAdd(true)}><Icon name="plus" size={13} /> Add research</button>
        </div>
      ) : (
        <div className="card" style={{ marginTop: 16 }}>
          {filtered.map((r, i) => (
            <div key={r.id || i} className="list-card">
              <div>
                <div className="source">{r.source} · {r.date}</div>
                <div className="title">{r.title}</div>
                <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>
                  {r.industries.join(", ")} · {r.scope.join(", ")}
                </div>
                <div className="meta-row">
                  <span className="tag accent">{r.category}</span>
                  {r.industries.map(ind => <span key={ind} className="tag">{ind}</span>)}
                  {r.scope.map(s => <span key={s} className="tag info">{s}</span>)}
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
                <ConfDot level={r.conf} />
                <button className="btn sm">Open <Icon name="external" size={11} /></button>
              </div>
            </div>
          ))}
        </div>
      )}

      <AddResearchModal open={showAdd} onClose={() => setShowAdd(false)} onSaved={() => { loadItems(); setShowAdd(false); }} />
    </div>
  );
};

// ─── Add Research Modal ───
const AddResearchModal = ({ open, onClose, onSaved }) => {
  const [form, setForm] = React.useState({
    title: "", source: "", category: "", geo_scope: [], industry_tags: [], publish_date: "", confidentiality: "internal"
  });
  const [file, setFile] = React.useState(null);
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setForm({ title: "", source: "", category: "", geo_scope: [], industry_tags: [], publish_date: "", confidentiality: "internal" });
      setFile(null);
      setErrors({});
    }
  }, [open]);

  const validate = () => {
    const e = {};
    if (!form.title.trim()) e.title = "Required.";
    if (!form.source.trim()) e.source = "Required.";
    if (!form.category) e.category = "Required.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async () => {
    if (!validate()) return;
    setLoading(true);
    try {
      let gcs_path = "";
      if (file) {
        const resp = await PrimaAPI.uploadHubFile("research", file);
        gcs_path = resp.gcs_path || "";
      }
      await PrimaAPI.addResearch({ ...form, gcs_path });
      onSaved();
    } catch (e) {
      setErrors({ api: e.message || "Failed to add research item." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} size="lg"
           title="Add research item"
           sub="Tag external intelligence for the Prima Research pipeline."
           footer={<>
             <button className="btn ghost" onClick={onClose}>Cancel</button>
             <button className="btn primary" onClick={submit} disabled={loading}>
               {loading ? "Saving…" : <><Icon name="check" size={14} /> Save item</>}
             </button>
           </>}>
      <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>
        )}
        <Field label="Title" required error={errors.title}>
          <TextInput value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="e.g. State of Urban Mobility 2026" error={errors.title} autoFocus />
        </Field>
        <div className="grid-2">
          <Field label="Source / Publisher" required error={errors.source}>
            <Select value={form.source} onChange={v => setForm({ ...form, source: v })} options={TAXONOMY.publishers} error={errors.source} />
          </Field>
          <Field label="Research category" required error={errors.category}>
            <Select value={form.category} onChange={v => setForm({ ...form, category: v })} options={TAXONOMY.researchCats} error={errors.category} />
          </Field>
        </div>
        <div className="grid-2">
          <Field label="Geographic scope" optional>
            <MultiSelect values={form.geo_scope} onChange={v => setForm({ ...form, geo_scope: v })} options={TAXONOMY.regions} />
          </Field>
          <Field label="Industry tags" optional>
            <MultiSelect values={form.industry_tags} onChange={v => setForm({ ...form, industry_tags: v })} options={TAXONOMY.industries} />
          </Field>
        </div>
        <div className="grid-2">
          <Field label="Publish date" optional>
            <TextInput value={form.publish_date} onChange={e => setForm({ ...form, publish_date: e.target.value })} placeholder="e.g. Apr 2026" />
          </Field>
          <Field label="Confidentiality" required>
            <Select value={form.confidentiality} onChange={v => setForm({ ...form, confidentiality: v })} options={TAXONOMY.confidentiality.map(c => c.id)} />
          </Field>
        </div>
        <Field label="Document" optional hint="Upload the source document — stored in the Research Hub folder.">
          <div className="hub-file-pick">
            <label className="hub-file-btn">
              <Icon name="upload" size={13} />
              {file ? file.name : "Choose file…"}
              <input type="file" style={{ display: "none" }} onChange={e => setFile(e.target.files[0] || null)} />
            </label>
            {file && <button className="hub-file-clear" onClick={() => setFile(null)}><Icon name="x" size={12} /></button>}
          </div>
        </Field>
      </div>
    </Modal>
  );
};


const ThoughtLeadership = () => {
  const [type, setType] = React.useState("all");
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showAdd, setShowAdd] = React.useState(false);

  const loadItems = () => {
    setLoading(true);
    PrimaAPI.listThought()
      .then(data => setItems(data || []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  };

  React.useEffect(() => { loadItems(); }, []);

  // Map API fields to display format
  const display = items.map(p => ({
    id: p.id,
    title: p.title,
    type: p.content_type,
    domain: p.primary_domain || "—",
    themes: p.themes || [],
    authors: p.authors || [],
    date: p.publish_date || "—",
    conf: p.confidentiality || "internal",
  }));

  const filtered = display.filter(p => type === "all" || p.type === type);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow"><Icon name="mic" size={11} /> Internal POVs</div>
          <h1 className="page-title">Thought <em>Leadership</em></h1>
          <p className="page-sub">Articles, op-eds, and whitepapers authored by Primus consultants — the firm's external voice, organised by domain and theme.</p>
        </div>
        <button className="btn primary" onClick={() => setShowAdd(true)}><Icon name="plus" size={14} /> Publish POV</button>
      </div>

      <div className="filter-rail">
        <div className="pill-group">
          {["all", ...TAXONOMY.contentTypes].map(c => (
            <button key={c} data-active={type === c} onClick={() => setType(c)}>{c === "all" ? "All" : c}</button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="empty" style={{ marginTop: 24 }}>
          <div style={{ color: "var(--fg-muted)", fontFamily: "var(--font-mono)", fontSize: 13 }}>Loading…</div>
        </div>
      ) : filtered.length === 0 ? (
        <div className="empty" style={{ marginTop: 24 }}>
          <div className="icon"><Icon name="mic" size={20} /></div>
          <h3>No thought leadership items yet</h3>
          <p>Publish internal POVs to build the firm's voice.</p>
          <button className="btn primary" onClick={() => setShowAdd(true)}><Icon name="plus" size={13} /> Publish POV</button>
        </div>
      ) : (
        <div className="grid-2" style={{ marginTop: 16 }}>
          {filtered.map((p, i) => (
            <div key={p.id || i} className="card" style={{ cursor: "pointer" }}>
              <div className="card-body">
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
                  <span className="tag accent">{p.type}</span>
                  <span className="tag">{p.domain}</span>
                  <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-subtle)" }}>
                    <Icon name="calendar" size={10} /> {p.date}
                  </span>
                </div>
                <h3 style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 500, letterSpacing: "-0.01em", margin: "0 0 6px", lineHeight: 1.2 }}>
                  {p.title}
                </h3>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, paddingTop: 12, borderTop: "1px dashed var(--hairline)" }}>
                  <div style={{ display: "flex", marginLeft: -3 }}>
                    {p.authors.map((a, ai) => (
                      <div key={a} style={{ marginLeft: ai === 0 ? 0 : -8, border: "2px solid var(--bg-elev)", borderRadius: 999 }}>
                        <Avatar name={a} size={26} />
                      </div>
                    ))}
                  </div>
                  <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>{p.authors.join(" · ")}</span>
                  <span style={{ marginLeft: "auto" }}>
                    <ConfDot level={p.conf} />
                  </span>
                </div>
                <div className="meta-row" style={{ marginTop: 10 }}>
                  {p.themes.map(t => <span key={t} className="tag"><Icon name="tag" size={9} /> {t}</span>)}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      <AddThoughtModal open={showAdd} onClose={() => setShowAdd(false)} onSaved={() => { loadItems(); setShowAdd(false); }} />
    </div>
  );
};

// ─── Add Thought Leadership Modal ───
const AddThoughtModal = ({ open, onClose, onSaved }) => {
  const [form, setForm] = React.useState({
    title: "", content_type: "", primary_domain: "", themes: [], authors: [], publish_date: "", confidentiality: "internal"
  });
  const [file, setFile] = React.useState(null);
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setForm({ title: "", content_type: "", primary_domain: "", themes: [], authors: [], publish_date: "", confidentiality: "internal" });
      setFile(null);
      setErrors({});
    }
  }, [open]);

  const validate = () => {
    const e = {};
    if (!form.title.trim()) e.title = "Required.";
    if (!form.content_type) e.content_type = "Required.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = async () => {
    if (!validate()) return;
    setLoading(true);
    try {
      let gcs_path = "";
      if (file) {
        const resp = await PrimaAPI.uploadHubFile("thought-leadership", file);
        gcs_path = resp.gcs_path || "";
      }
      await PrimaAPI.addThought({ ...form, gcs_path });
      onSaved();
    } catch (e) {
      setErrors({ api: e.message || "Failed to publish POV." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} size="lg"
           title="Publish thought leadership"
           sub="Capture internal POVs for domain expertise visibility."
           footer={<>
             <button className="btn ghost" onClick={onClose}>Cancel</button>
             <button className="btn primary" onClick={submit} disabled={loading}>
               {loading ? "Publishing…" : <><Icon name="check" size={14} /> Publish</>}
             </button>
           </>}>
      <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>
        )}
        <Field label="Title" required error={errors.title}>
          <TextInput value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} placeholder="e.g. Why citizen-experience must lead digital-government roadmaps" error={errors.title} autoFocus />
        </Field>
        <div className="grid-2">
          <Field label="Content type" required error={errors.content_type}>
            <Select value={form.content_type} onChange={v => setForm({ ...form, content_type: v })} options={TAXONOMY.contentTypes} error={errors.content_type} />
          </Field>
          <Field label="Primary domain" optional>
            <Select value={form.primary_domain} onChange={v => setForm({ ...form, primary_domain: v })} options={TAXONOMY.domains} placeholder="Optional…" />
          </Field>
        </div>
        <Field label="Themes" optional hint="Key topics covered in the piece.">
          <MultiSelect values={form.themes} onChange={v => setForm({ ...form, themes: v })} options={["Generative AI", "Agentic AI", "Urbanization", "Climate", "Disclosure", "Citizen Services", "Programme Mgmt", "Banking", "Health"]} allowCustom />
        </Field>
        <Field label="Authors" optional hint="Internal Primus authors.">
          <MultiSelect values={form.authors} onChange={v => setForm({ ...form, authors: v })} options={[]} allowCustom />
        </Field>
        <div className="grid-2">
          <Field label="Publish date" optional>
            <TextInput value={form.publish_date} onChange={e => setForm({ ...form, publish_date: e.target.value })} placeholder="e.g. Apr 24, 2026" />
          </Field>
          <Field label="Confidentiality" required>
            <Select value={form.confidentiality} onChange={v => setForm({ ...form, confidentiality: v })} options={TAXONOMY.confidentiality.map(c => c.id)} />
          </Field>
        </div>
        <Field label="Document" optional hint="Attach the published piece — stored in the Thought Leadership folder.">
          <div className="hub-file-pick">
            <label className="hub-file-btn">
              <Icon name="upload" size={13} />
              {file ? file.name : "Choose file…"}
              <input type="file" style={{ display: "none" }} onChange={e => setFile(e.target.files[0] || null)} />
            </label>
            {file && <button className="hub-file-clear" onClick={() => setFile(null)}><Icon name="x" size={12} /></button>}
          </div>
        </Field>
      </div>
    </Modal>
  );
};

Object.assign(window, { ResearchHub, ThoughtLeadership, AddResearchModal, AddThoughtModal });
