// ============ TaskQuest — System Admin panel ============
const { useState: useStateA } = React;
const { ROLES: RAd, PROJECTS: PAd } = window.TQ;

function AdminCard({ icon, iconColor, title, sub, children }) {
  return (
    <div className="admin-card">
      <div className="admin-card-head">
        <span className="stat-ic" style={{ background: iconColor + "22", color: iconColor }}>{React.createElement(icon, { size: 16 })}</span>
        <div>
          <div className="admin-card-title">{title}</div>
          {sub && <div className="admin-card-sub">{sub}</div>}
        </div>
      </div>
      {children}
    </div>
  );
}

function ProjectPicker({ value, onChange }) {
  const projects = Object.values(window.TQ.PROJECTS);
  const sel = Array.isArray(value) ? value : [];
  function toggle(k) {
    onChange(sel.includes(k) ? sel.filter(x => x !== k) : [...sel, k]);
  }
  if (projects.length === 0) {
    return <div className="comment-empty" style={{ padding: "8px 2px" }}>No projects yet — add one in the Projects card first.</div>;
  }
  return (
    <div className="proj-picker">
      {projects.map(p => {
        const on = sel.includes(p.key);
        return (
          <button type="button" key={p.key} className={`proj-chip ${on ? "on" : ""}`} onClick={() => toggle(p.key)}>
            <span className="pdot-sm" style={{ background: p.color }} />
            <span className="proj-chip-name">{p.name}</span>
            {on && <Ic.Check size={13} />}
          </button>
        );
      })}
    </div>
  );
}

function UserRow({ u, onEdit }) {
  const r = window.TQ.ROLES[u];
  if (!r) return null;
  const projs = window.TQ.projectsOf(r);
  return (
    <div className="admin-row" key={u}>
      <Avatar who={u} size="sm" />
      <span className="admin-row-name">{r.name}</span>
      {r.username && <span className="admin-row-user">@{r.username}</span>}
      {projs.length > 0 && (
        <span className="admin-row-projs">
          {projs.slice(0, 2).map(k => (
            <span className="admin-row-proj" key={k}><span className="pdot-sm" style={{ background: window.TQ.PROJECTS[k].color }} />{window.TQ.PROJECTS[k].name}</span>
          ))}
          {projs.length > 2 && <span className="admin-row-proj more">+{projs.length - 2}</span>}
        </span>
      )}
      <span className={`role-tag t-${r.type}`}>{r.label}</span>
      <button className="icon-btn admin-edit-btn" title="Edit profile" onClick={() => onEdit(u)}><Ic.Edit size={15} /></button>
    </div>
  );
}

function EditUserForm({ id, live, isSelf, onSave, onDelete, onCancel }) {
  const r = window.TQ.ROLES[id] || {};
  const [name, setName] = useStateA(r.name || "");
  const [uname, setUname] = useStateA(r.username || "");
  const [type, setType] = useStateA(r.type || "consultant");
  const [projs, setProjs] = useStateA(window.TQ.projectsOf(r));
  const [pw, setPw] = useStateA("");
  const [show, setShow] = useStateA(false);
  const [busy, setBusy] = useStateA(false);
  const [msg, setMsg] = useStateA(null);
  const [confirmDel, setConfirmDel] = useStateA(false);
  const pwOk = pw === "" || pw.length >= 6;
  const valid = name.trim().length > 1 && pwOk;

  async function save() {
    if (!valid || busy) return;
    setBusy(true); setMsg(null);
    const res = await onSave({ id, name: name.trim(), username: uname.trim() || null, type, projects: projs, password: pw || null });
    setBusy(false);
    if (res && res.ok) { onCancel(); }
    else { setMsg({ ok: false, text: (res && res.message) || "Could not update the profile." }); }
  }

  async function remove() {
    if (busy) return;
    setBusy(true); setMsg(null);
    const res = await onDelete(id);
    setBusy(false);
    if (res && res.ok) { onCancel(); }
    else { setConfirmDel(false); setMsg({ ok: false, text: (res && res.message) || "Could not remove the user." }); }
  }

  return (
    <div className="admin-edit-form">
      <div className="admin-form-title"><Ic.Edit size={13} />Edit profile</div>
      <div className="field">
        <label className="field-label">Full name</label>
        <input className="input" value={name} onChange={e => { setName(e.target.value); setMsg(null); }} />
      </div>
      <div className="admin-form-row">
        <div className="field" style={{ flex: 1 }}>
          <label className="field-label">Username</label>
          <input className="input" placeholder="jordan.lee" value={uname} onChange={e => setUname(e.target.value)} />
        </div>
        <div className="field" style={{ flex: 1 }}>
          <label className="field-label">Profile type</label>
          <select className="input" value={type} onChange={e => setType(e.target.value)}>
            <option value="consultant">Consultant</option>
            <option value="pm">Project Manager</option>
            <option value="dm">Delivery Manager</option>
            <option value="admin">System Admin</option>
          </select>
        </div>
      </div>
      <div className="field">
        <label className="field-label">Projects <span style={{ color: "var(--faint)", fontWeight: 500 }}>· select one or more</span></label>
        <ProjectPicker value={projs} onChange={setProjs} />
      </div>
      <div className="field">
        <label className="field-label">Reset password <span style={{ color: "var(--faint)", fontWeight: 500 }}>· leave blank to keep current</span></label>
        <div className="login-pw-wrap">
          <input className="input" type={show ? "text" : "password"} placeholder="New password (min 6 characters)" value={pw}
            onChange={e => { setPw(e.target.value); setMsg(null); }} />
          <button type="button" className="login-pw-toggle" onClick={() => setShow(s => !s)} title={show ? "Hide" : "Show"}>
            {show ? <Ic.EyeOff size={16} /> : <Ic.Eye size={16} />}
          </button>
        </div>
        {!pwOk && <div className="login-hint" style={{ color: "#eb5757" }}>Password must be at least 6 characters.</div>}
      </div>
      {msg && (
        <div className="admin-msg" style={{ color: "#eb5757", background: "#eb575714" }}>
          <Ic.Alert size={14} /><span>{msg.text}</span>
        </div>
      )}
      <div className="admin-form-row" style={{ marginTop: 2 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={onCancel} disabled={busy}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1 }} disabled={!valid || busy} onClick={save}>
          <Ic.Check size={15} />{busy ? "Saving…" : "Save changes"}
        </button>
      </div>

      {/* Danger zone — remove the user entirely */}
      <div className="admin-danger">
        {!confirmDel ? (
          <button className="btn btn-soft-danger btn-block" disabled={busy || isSelf} onClick={() => { setConfirmDel(true); setMsg(null); }}>
            <Ic.Trash size={15} />Remove user
          </button>
        ) : (
          <div className="admin-danger-confirm">
            <div className="admin-danger-text">Permanently delete <b>{r.name}</b>? Their login is removed and their tasks are left unassigned. This can't be undone.</div>
            <div className="admin-form-row">
              <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => setConfirmDel(false)} disabled={busy}>Keep user</button>
              <button className="btn btn-danger" style={{ flex: 1 }} onClick={remove} disabled={busy}>
                <Ic.Trash size={15} />{busy ? "Removing…" : "Delete permanently"}
              </button>
            </div>
          </div>
        )}
        {isSelf && <div className="login-hint" style={{ marginTop: 6 }}>You can't delete the account you're signed in with.</div>}
      </div>
      {!live && <div className="login-hint" style={{ marginTop: 2 }}>Preview mode — changes are kept locally only.</div>}
    </div>
  );
}

function UsersAdmin({ onCreate, onUpdate, onDelete, meId }) {
  const live = window.TQ_BACKEND.CONFIGURED;
  const [name, setName] = useStateA("");
  const [email, setEmail] = useStateA("");
  const [uname, setUname] = useStateA("");
  const [pw, setPw] = useStateA("");
  const [type, setType] = useStateA("consultant");
  const [projs, setProjs] = useStateA([]);
  const [show, setShow] = useStateA(false);
  const [busy, setBusy] = useStateA(false);
  const [msg, setMsg] = useStateA(null); // { ok, text }
  const [editId, setEditId] = useStateA(null);

  const users = [...window.TQ.CONSULTANTS, ...window.TQ.MANAGERS, ...Object.keys(window.TQ.ROLES).filter(k => window.TQ.ROLES[k].type === "admin")];
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const valid = name.trim().length > 1 && emailOk && pw.length >= 6;

  async function submit() {
    if (!valid || busy) return;
    setBusy(true); setMsg(null);
    const res = await onCreate({ name: name.trim(), email: email.trim(), username: uname.trim() || null, password: pw, type, projects: projs });
    setBusy(false);
    if (res && res.ok) {
      setMsg({ ok: true, text: `Login created. Share the email + password with ${name.trim()}.` });
      setName(""); setEmail(""); setUname(""); setPw(""); setType("consultant"); setProjs([]);
    } else {
      setMsg({ ok: false, text: (res && res.message) || "Could not create the account." });
    }
  }

  return (
    <AdminCard icon={Ic.Users} iconColor="#5E6AD2" title="Team members"
      sub={`${users.length} ${users.length === 1 ? "person" : "people"} · ${window.TQ.CONSULTANTS.length} consultant${window.TQ.CONSULTANTS.length === 1 ? "" : "s"}`}>
      <div className="admin-list">
        {users.length === 0 && <div className="comment-empty" style={{ padding: "14px 4px" }}>No members yet — provision the first account below.</div>}
        {users.map(u => (
          editId === u
            ? <EditUserForm key={u} id={u} live={live} isSelf={u === meId} onSave={onUpdate} onDelete={onDelete} onCancel={() => setEditId(null)} />
            : <UserRow key={u} u={u} onEdit={(id) => { setEditId(id); setMsg(null); }} />
        ))}
      </div>

      <div className="admin-form">
        <div className="admin-form-title"><Ic.Plus size={13} />Provision a login</div>
        <div className="field">
          <label className="field-label">Full name</label>
          <input className="input" placeholder="e.g. Jordan Lee" value={name}
            onChange={e => { setName(e.target.value); setMsg(null); }} />
        </div>
        <div className="field">
          <label className="field-label">Email address</label>
          <input className="input" type="email" placeholder="jordan@company.com" value={email}
            onChange={e => { setEmail(e.target.value); setMsg(null); }} />
        </div>
        <div className="admin-form-row">
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Username <span style={{ color: "var(--faint)", fontWeight: 500 }}>· optional</span></label>
            <input className="input" placeholder="jordan.lee" value={uname}
              onChange={e => { setUname(e.target.value); setMsg(null); }} />
          </div>
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Profile type</label>
            <select className="input" value={type} onChange={e => setType(e.target.value)}>
              <option value="consultant">Consultant</option>
              <option value="pm">Project Manager</option>
              <option value="dm">Delivery Manager</option>
              <option value="admin">System Admin</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label className="field-label">Projects <span style={{ color: "var(--faint)", fontWeight: 500 }}>· {type === "dm" || type === "admin" ? "optional — this role spans all projects" : "assign one or more"}</span></label>
          <ProjectPicker value={projs} onChange={p => { setProjs(p); setMsg(null); }} />
        </div>
        <div className="field">
          <label className="field-label">Temporary password <span style={{ color: "var(--faint)", fontWeight: 500 }}>· min 6 characters</span></label>
          <div className="login-pw-wrap">
            <input className="input" type={show ? "text" : "password"} placeholder="Set an initial password" value={pw}
              onChange={e => { setPw(e.target.value); setMsg(null); }} />
            <button type="button" className="login-pw-toggle" onClick={() => setShow(s => !s)} title={show ? "Hide" : "Show"}>
              {show ? <Ic.EyeOff size={16} /> : <Ic.Eye size={16} />}
            </button>
          </div>
        </div>

        {msg && (
          <div className="admin-msg" style={{ color: msg.ok ? "#16a394" : "#eb5757", background: (msg.ok ? "#16a394" : "#eb5757") + "14" }}>
            {React.createElement(msg.ok ? Ic.CheckCircle : Ic.Alert, { size: 14 })}
            <span>{msg.text}</span>
          </div>
        )}

        <button className="btn btn-primary" disabled={!valid || busy} onClick={submit}>
          <Ic.Plus size={15} />{busy ? "Creating…" : "Create login"}
        </button>
        {!live && <div className="login-hint" style={{ marginTop: 2 }}>Preview mode — the account is created locally and not saved.</div>}
      </div>
    </AdminCard>
  );
}

function ProjectEditForm({ pk, onSave, onDelete, onCancel }) {
  const p = window.TQ.PROJECTS[pk] || {};
  const [name, setName] = useStateA(p.name || "");
  const [color, setColor] = useStateA(p.color || window.TQ.PALETTE[0]);
  const [busy, setBusy] = useStateA(false);
  const [msg, setMsg] = useStateA(null);
  const [confirmDel, setConfirmDel] = useStateA(false);
  const valid = name.trim().length > 1;

  async function save() {
    if (!valid || busy) return;
    setBusy(true); setMsg(null);
    const res = await onSave(pk, { name: name.trim(), color });
    setBusy(false);
    if (res && res.ok) onCancel();
    else setMsg((res && res.message) || "Could not update the project.");
  }
  async function remove() {
    if (busy) return;
    setBusy(true); setMsg(null);
    const res = await onDelete(pk);
    setBusy(false);
    if (res && res.ok) onCancel();
    else { setConfirmDel(false); setMsg((res && res.message) || "Could not remove the project."); }
  }

  return (
    <div className="admin-edit-form">
      <div className="admin-form-title"><Ic.Edit size={13} />Edit project</div>
      <div className="field">
        <label className="field-label">Project name</label>
        <input className="input" value={name} onChange={e => { setName(e.target.value); setMsg(null); }}
          onKeyDown={e => { if (e.key === "Enter") save(); }} />
      </div>
      <div className="field">
        <label className="field-label">Color</label>
        <div className="swatch-row">
          {window.TQ.PALETTE.map(c => (
            <button key={c} className={`swatch ${color === c ? "sel" : ""}`} style={{ background: c }} onClick={() => setColor(c)} />
          ))}
        </div>
      </div>
      {msg && <div className="admin-msg" style={{ color: "#eb5757", background: "#eb575714" }}><Ic.Alert size={14} /><span>{msg}</span></div>}
      <div className="admin-form-row" style={{ marginTop: 2 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={onCancel} disabled={busy}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1 }} disabled={!valid || busy} onClick={save}><Ic.Check size={15} />{busy ? "Saving…" : "Save changes"}</button>
      </div>
      <div className="admin-danger">
        {!confirmDel ? (
          <button className="btn btn-soft-danger btn-block" disabled={busy} onClick={() => { setConfirmDel(true); setMsg(null); }}><Ic.Trash size={15} />Remove project</button>
        ) : (
          <div className="admin-danger-confirm">
            <div className="admin-danger-text">Delete <b>{p.name}</b>? Tasks in this project are kept but left without a project. This can't be undone.</div>
            <div className="admin-form-row">
              <button className="btn btn-ghost" style={{ flex: 1 }} onClick={() => setConfirmDel(false)} disabled={busy}>Keep project</button>
              <button className="btn btn-danger" style={{ flex: 1 }} onClick={remove} disabled={busy}><Ic.Trash size={15} />{busy ? "Removing…" : "Delete permanently"}</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function ProjectsAdmin({ onCreate, onCreateMany, onEdit, onDelete }) {
  const [mode, setMode] = useStateA("single"); // 'single' | 'bulk'
  const [name, setName] = useStateA("");
  const [color, setColor] = useStateA(window.TQ.PALETTE[0]);
  const [bulk, setBulk] = useStateA("");
  const [busy, setBusy] = useStateA(false);
  const [editKey, setEditKey] = useStateA(null);
  const projects = Object.values(window.TQ.PROJECTS);
  const valid = name.trim().length > 1;

  // parse one-project-per-line (also tolerates commas), de-duped, trimmed
  const bulkNames = Array.from(new Set(
    bulk.split(/[\n,]+/).map(s => s.trim()).filter(s => s.length > 1)
  ));

  function nextColor(usedExtra) {
    const used = Object.values(window.TQ.PROJECTS).map(p => p.color).concat(usedExtra || []);
    return window.TQ.PALETTE.find(c => !used.includes(c)) || window.TQ.PALETTE[(used.length) % window.TQ.PALETTE.length];
  }

  function submitSingle() {
    if (!valid) return;
    onCreate({ name: name.trim(), color });
    setName("");
    setColor(nextColor());
  }

  async function submitBulk() {
    if (!bulkNames.length || busy) return;
    setBusy(true);
    const used = [];
    const list = bulkNames.map(nm => { const c = nextColor(used); used.push(c); return { name: nm, color: c }; });
    const res = await onCreateMany(list);
    setBusy(false);
    if (!res || res.ok) setBulk("");
  }

  return (
    <AdminCard icon={Ic.Folder} iconColor="#16a394" title="Projects" sub={`${projects.length} active`}>
      <div className="admin-list">
        {projects.length === 0 && <div className="comment-empty" style={{ padding: "14px 4px" }}>No projects yet — add one below.</div>}
        {projects.map(p => (
          editKey === p.key
            ? <ProjectEditForm key={p.key} pk={p.key} onSave={onEdit} onDelete={onDelete} onCancel={() => setEditKey(null)} />
            : (
              <div className="admin-row" key={p.key}>
                <span className="pdot" style={{ width: 12, height: 12, borderRadius: "50%", background: p.color }} />
                <span className="admin-row-name">{p.name}</span>
                <span className="role-tag t-muted">{p.key}</span>
                <button className="icon-btn admin-edit-btn" title="Edit project" onClick={() => setEditKey(p.key)}><Ic.Edit size={15} /></button>
              </div>
            )
        ))}
      </div>
      <div className="admin-form">
        <div className="seg-toggle">
          <button className={`seg-btn ${mode === "single" ? "sel" : ""}`} onClick={() => setMode("single")}>Add one</button>
          <button className={`seg-btn ${mode === "bulk" ? "sel" : ""}`} onClick={() => setMode("bulk")}>Add several</button>
        </div>
        {mode === "single" ? (
          <>
            <input className="input" placeholder="Project name…" value={name} onChange={e => setName(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") submitSingle(); }} />
            <div className="swatch-row">
              {window.TQ.PALETTE.map(c => (
                <button key={c} className={`swatch ${color === c ? "sel" : ""}`} style={{ background: c }} onClick={() => setColor(c)} />
              ))}
            </div>
            <button className="btn btn-primary" disabled={!valid} onClick={submitSingle}><Ic.Plus size={15} />Create project</button>
          </>
        ) : (
          <>
            <label className="field-label">One project per line <span style={{ color: "var(--faint)", fontWeight: 500 }}>· colors auto-assigned</span></label>
            <textarea className="textarea" style={{ minHeight: 92 }} placeholder={"Project Delta\nProject Epsilon\nProject Zeta"}
              value={bulk} onChange={e => setBulk(e.target.value)} />
            <button className="btn btn-primary" disabled={!bulkNames.length || busy} onClick={submitBulk}>
              <Ic.Plus size={15} />{busy ? "Creating…" : bulkNames.length ? `Create ${bulkNames.length} project${bulkNames.length === 1 ? "" : "s"}` : "Create projects"}
            </button>
          </>
        )}
      </div>
    </AdminCard>
  );
}

function PointsAdmin({ onSave }) {
  const cfg = window.TQ.CONFIG;
  const [ontime, setOntime] = useStateA(cfg.onTimePoints);
  const [late, setLate] = useStateA(cfg.latePoints);
  const [tiers, setTiers] = useStateA(cfg.bonusTiers.join(", "));
  const [saved, setSaved] = useStateA(false);

  function save() {
    const parsed = tiers.split(",").map(s => parseInt(s.trim(), 10)).filter(n => !isNaN(n) && n > 0);
    onSave({
      onTimePoints: Math.max(0, parseInt(ontime, 10) || 0),
      latePoints: Math.max(0, parseInt(late, 10) || 0),
      bonusTiers: parsed.length ? parsed.slice(0, 4) : [5, 10, 20],
    });
    setSaved(true); setTimeout(() => setSaved(false), 1800);
  }

  return (
    <AdminCard icon={Ic.Target} iconColor="#e0902b" title="Points system" sub="Drives every leaderboard & score">
      <div className="points-grid">
        <div className="points-field">
          <label className="field-label">On-time completion</label>
          <div className="num-wrap">
            <input className="input" type="number" min="0" value={ontime} onChange={e => setOntime(e.target.value)} />
            <span className="num-suffix">pts</span>
          </div>
        </div>
        <div className="points-field">
          <label className="field-label">Late completion</label>
          <div className="num-wrap">
            <input className="input" type="number" min="0" value={late} onChange={e => setLate(e.target.value)} />
            <span className="num-suffix">pts</span>
          </div>
        </div>
      </div>
      <div className="field" style={{ marginTop: 14 }}>
        <label className="field-label">Bonus award tiers <span style={{ color: "var(--faint)", fontWeight: 500 }}>· comma-separated</span></label>
        <input className="input" value={tiers} onChange={e => setTiers(e.target.value)} placeholder="5, 10, 20" />
      </div>
      <div className="formula-box">
        <div className="formula-row"><span className="formula-k">Performance score</span><span className="formula-v">(On-time ÷ Total assigned) × 100</span></div>
        <div className="formula-row"><span className="formula-k">Leaderboard rank</span><span className="formula-v">Total points, then performance %</span></div>
      </div>
      <button className="btn btn-primary btn-block" onClick={save} style={{ marginTop: 14 }}>
        {saved ? <><Ic.Check size={15} />Saved</> : <>Save points system</>}
      </button>
    </AdminCard>
  );
}

function AdminPanel({ meId, onCreateUser, onUpdateUser, onDeleteUser, onCreateProject, onCreateProjects, onEditProject, onDeleteProject, onSaveConfig }) {
  return (
    <div className="admin-grid">
      <UsersAdmin onCreate={onCreateUser} onUpdate={onUpdateUser} onDelete={onDeleteUser} meId={meId} />
      <div className="admin-col">
        <ProjectsAdmin onCreate={onCreateProject} onCreateMany={onCreateProjects} onEdit={onEditProject} onDelete={onDeleteProject} />
        <PointsAdmin onSave={onSaveConfig} />
      </div>
    </div>
  );
}

window.AdminPanel = AdminPanel;
