/* ============================================================
   Admin — Team management (CEO only)
   Create/edit users; set vacation allowance, working pattern,
   weekly hours — the basis for balance & deductions.
   ============================================================ */
const { useState, useEffect, useRef } = React;

const WEEKDAYS = [
  { d: 1, label: "Mon" }, { d: 2, label: "Tue" }, { d: 3, label: "Wed" },
  { d: 4, label: "Thu" }, { d: 5, label: "Fri" }, { d: 6, label: "Sat" }, { d: 0, label: "Sun" },
];
const NEW_COLORS = ["#5A58E7", "#3490EB", "#7D50CA", "#2F6FD0", "#8A5FC2", "#6E78D6", "#C99A0E", "#5C6680"];

function formatPattern(workdays) {
  const wd = [...workdays].sort((a, b) => (a === 0 ? 7 : a) - (b === 0 ? 7 : b));
  if (wd.length === 5 && [1, 2, 3, 4, 5].every((x) => wd.includes(x))) return "Mon–Fri";
  const map = { 0: "Sun", 1: "Mon", 2: "Tue", 3: "Wed", 4: "Thu", 5: "Fri", 6: "Sat" };
  return wd.map((d) => map[d]).join(", ");
}

const labelStyle = { fontSize: 13.5, fontWeight: 600, color: "var(--ink-2)", marginBottom: 9 };

/* ---- Number stepper ---- */
function Stepper({ value, onChange, min = 0, max = 60, step = 1, suffix }) {
  const btn = { width: 34, height: 38, display: "grid", placeItems: "center", border: "1px solid var(--line-2)", background: "var(--surface)", cursor: "pointer", color: "var(--ink-2)" };
  return (
    <div style={{ display: "inline-flex", alignItems: "stretch", borderRadius: "var(--r-sm)", overflow: "hidden", border: "1px solid var(--line-2)" }}>
      <button type="button" onClick={() => onChange(Math.max(min, +(value - step).toFixed(1)))} style={{ ...btn, borderTop: "none", borderBottom: "none", borderLeft: "none" }}>
        <span style={{ width: 12, height: 2, borderRadius: 2, background: "currentColor" }} />
      </button>
      <div style={{ minWidth: 70, display: "flex", alignItems: "center", justifyContent: "center", gap: 4, fontWeight: 700, fontFamily: "var(--font-display)", fontSize: 16, background: "var(--surface)" }}>
        {value}{suffix && <span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 600 }}>{suffix}</span>}
      </div>
      <button type="button" onClick={() => onChange(Math.min(max, +(value + step).toFixed(1)))} style={{ ...btn, borderTop: "none", borderBottom: "none", borderRight: "none" }}>
        <Icon name="plus" size={14} stroke={2} />
      </button>
    </div>
  );
}

/* ---- Person form (create / edit) ---- */
function PersonForm({ person, onSave, onClose, onArchive }) {
  const editing = !!person;
  const [first, setFirst] = useState(person?.first || "");
  const [last, setLast] = useState(person?.last || "");
  const [email, setEmail] = useState(person?.email || "");
  const [role, setRole] = useState(person?.role || "employee");
  const [team, setTeam] = useState(person?.team || "");
  const [allowance, setAllowance] = useState(person?.allowance ?? 30);
  const [hours, setHours] = useState(person?.weeklyHours ?? 40);
  const [workdays, setWorkdays] = useState(person?.workdays || [1, 2, 3, 4, 5]);
  const [start, setStart] = useState(person?.startDate || TODAY);
  const [err, setErr] = useState("");
  const narrow = useIsNarrow(820);
  const twoCol = narrow ? "1fr" : "1fr 1fr";

  const teams = [...new Set(VP_DATA.people.map((p) => p.team))];

  function toggleDay(d) {
    setWorkdays((w) => w.includes(d) ? w.filter((x) => x !== d) : [...w, d]);
  }

  function save() {
    if (!first.trim() || !last.trim()) { setErr("First and last name are required."); return; }
    if (!/^\S+@\S+\.\S+$/.test(email.trim())) { setErr("Enter a valid email address."); return; }
    const dup = VP_DATA.people.find((p) => p.email.toLowerCase() === email.trim().toLowerCase() && p.id !== person?.id);
    if (dup) { setErr("Another person already uses that email."); return; }
    if (workdays.length === 0) { setErr("Select at least one working day."); return; }
    const id = person?.id || ("p_" + first.trim().toLowerCase().replace(/\W/g, "") + Date.now() % 100000);
    const color = person?.color || NEW_COLORS[VP_DATA.people.length % NEW_COLORS.length];
    onSave({
      id, first: first.trim(), last: last.trim(), email: email.trim(), role,
      team: team.trim() || "Team", color, allowance: Number(allowance),
      weeklyHours: Number(hours), workdays: [...workdays], startDate: start,
    }, !editing);
  }

  return (
    <div>
      <div style={{ height: 6, background: "linear-gradient(90deg,#3490EB,#5A58E7 55%,#7D50CA)", borderRadius: "var(--r-xl) var(--r-xl) 0 0" }} />
      <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <h2 style={{ fontSize: 22 }}>{editing ? `Edit ${person.first} ${person.last}` : "Add a person"}</h2>
        <button type="button" onClick={onClose} className="vp-focusable" style={{ width: 36, height: 36, display: "grid", placeItems: "center", borderRadius: "var(--r-sm)", border: "none", background: "var(--paper-2)", cursor: "pointer" }}><Icon name="x" size={18} /></button>
      </div>

      <div style={{ padding: "22px 26px", display: "grid", gap: 20 }}>
        {/* Identity */}
        <div style={{ display: "grid", gridTemplateColumns: twoCol, gap: 14 }}>
          <Field label="First name"><Input value={first} onChange={setFirst} placeholder="Jamie" /></Field>
          <Field label="Last name"><Input value={last} onChange={setLast} placeholder="Wagner" /></Field>
        </div>
        <Field label="Work email"><Input value={email} onChange={setEmail} placeholder="jamie.wagner@mesper.de" type="email" /></Field>

        <div style={{ display: "grid", gridTemplateColumns: twoCol, gap: 14 }}>
          <Field label="Role & access">
            <div style={{ display: "inline-flex", background: "var(--paper-2)", borderRadius: "var(--r-sm)", padding: 4, width: "100%" }}>
              {[["employee", "Employee"], ["ceo", "CEO · Admin"]].map(([id, lbl]) => (
                <button key={id} type="button" onClick={() => setRole(id)}
                  style={{ flex: 1, border: "none", cursor: "pointer", padding: "8px 10px", borderRadius: "var(--r-xs)", fontWeight: 600, fontSize: 13, fontFamily: "var(--font-body)",
                    background: role === id ? "var(--surface)" : "transparent", color: role === id ? "var(--ink)" : "var(--ink-3)", boxShadow: role === id ? "var(--sh-sm)" : "none" }}>{lbl}</button>
              ))}
            </div>
          </Field>
          <Field label="Team">
            <Input value={team} onChange={setTeam} placeholder="e.g. Design" list="teamlist" />
            <datalist id="teamlist">{teams.map((t) => <option key={t} value={t} />)}</datalist>
          </Field>
        </div>

        {/* Entitlement block */}
        <div style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: "18px 18px 20px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16 }}>
            <Icon name="info" size={16} style={{ color: "var(--accent)" }} />
            <span style={{ fontWeight: 700, fontSize: 13.5, color: "var(--ink)" }}>Entitlement & working time</span>
            <span style={{ fontSize: 12, color: "var(--ink-3)" }}>— drives balance & deductions</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: twoCol, gap: 18 }}>
            <Field label="Annual vacation allowance"><Stepper value={allowance} onChange={setAllowance} min={0} max={60} suffix="days" /></Field>
            <Field label="Contracted hours / week"><Stepper value={hours} onChange={setHours} min={1} max={60} suffix="h" /></Field>
          </div>
          <div style={{ marginTop: 18 }}>
            <div style={labelStyle}>Working days <span style={{ fontWeight: 500, color: "var(--ink-4)" }}>· vacation is only deducted on these days</span></div>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
              {WEEKDAYS.map(({ d, label }) => {
                const on = workdays.includes(d);
                return (
                  <button key={d} type="button" onClick={() => toggleDay(d)}
                    style={{ width: 52, padding: "9px 0", textAlign: "center", borderRadius: "var(--r-sm)", cursor: "pointer", fontWeight: 600, fontSize: 13,
                      border: `1px solid ${on ? "transparent" : "var(--line-2)"}`, background: on ? "var(--accent)" : "var(--surface)", color: on ? "#fff" : "var(--ink-3)",
                      boxShadow: on ? "var(--sh-sm)" : "none", transition: "all .12s" }}>{label}</button>
                );
              })}
            </div>
          </div>
          <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: twoCol, gap: 18, alignItems: "end" }}>
            <Field label="Start date"><Input value={start} onChange={setStart} type="date" /></Field>
            <div style={{ fontSize: 13, color: "var(--ink-3)", paddingBottom: 10 }}>
              {workdays.length} working day{workdays.length === 1 ? "" : "s"}/week · {allowance} days off
            </div>
          </div>
        </div>

        {err && <div className="vp-fade" style={{ display: "flex", gap: 9, alignItems: "center", color: "var(--st-declined)", fontSize: 13.5, fontWeight: 500 }}><Icon name="info" size={17} /> {err}</div>}
      </div>

      <div style={{ padding: "16px 26px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", position: "sticky", bottom: 0, background: "var(--surface)" }}>
        <span>{editing && onArchive && <Button variant="ghost" size="sm" onClick={() => onArchive(person)} style={{ color: "var(--st-declined)" }}>Remove access</Button>}</span>
        <div style={{ display: "flex", gap: 10 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button icon="check" onClick={save}>{editing ? "Save changes" : "Create account"}</Button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return <label style={{ display: "block" }}><div style={labelStyle}>{label}</div>{children}</label>;
}
function Input({ value, onChange, placeholder, type = "text", list }) {
  const [foc, setFoc] = useState(false);
  return (
    <input value={value} list={list} type={type} placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)} onFocus={() => setFoc(true)} onBlur={() => setFoc(false)}
      className="vp-focusable"
      style={{ width: "100%", padding: "11px 13px", fontSize: 14.5, color: "var(--ink)", background: "var(--surface)",
        border: `1px solid ${foc ? "var(--accent)" : "var(--line-2)"}`, borderRadius: "var(--r-sm)", outline: "none",
        boxShadow: foc ? "0 0 0 3px var(--accent-soft)" : "none", transition: "all .15s" }} />
  );
}

/* ---- Team admin view ---- */
function TeamAdmin({ user, requests, onAddPerson, onEditPerson }) {
  const people = VP_DATA.people;
  const ceos = people.filter((p) => p.role === "ceo");
  const emps = people.filter((p) => p.role === "employee");

  return (
    <div className="vp-fade-up" style={{ display: "grid", gap: "var(--gap)" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ fontSize: 30 }}>Team &amp; entitlements</h1>
          <p style={{ color: "var(--ink-3)", margin: "6px 0 0", fontSize: 15 }}>Allowance, working pattern and hours per person — these drive every balance.</p>
        </div>
        <Button size="lg" icon="plus" onClick={onAddPerson}>Add person</Button>
      </div>

      <PeopleTable title="Leadership · Admins" people={ceos} requests={requests} onEditPerson={onEditPerson} />
      <PeopleTable title="Employees" people={emps} requests={requests} onEditPerson={onEditPerson} />
    </div>
  );
}

function PeopleTable({ title, people, requests, onEditPerson }) {
  return (
    <Card pad="0" style={{ overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "15px 20px", borderBottom: "1px solid var(--line)" }}>
        <SectionTitle count={people.length}>{title}</SectionTitle>
      </div>
      <div style={{ overflowX: "auto" }}>
        <div style={{ minWidth: 640 }}>
          {/* header */}
          <div style={{ display: "grid", gridTemplateColumns: "minmax(220px,2fr) 1.3fr 1fr 1.4fr 40px", gap: 12, padding: "10px 20px", borderBottom: "1px solid var(--line)", background: "var(--surface-2)" }}>
            {["Person", "Working pattern", "Allowance", "This year", ""].map((h, i) => (
              <div key={i} style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-4)", textAlign: "left" }}>{h}</div>
            ))}
          </div>
          <div>
            {people.map((p) => <PersonRow key={p.id} p={p} requests={requests} onEdit={() => onEditPerson(p)} />)}
          </div>
        </div>
      </div>
    </Card>
  );
}

function PersonRow({ p, requests, onEdit }) {
  const [hover, setHover] = useState(false);
  const bal = balanceFor(p.id, requests);
  const usedFrac = bal.allowance ? Math.min(bal.used / bal.allowance, 1) : 0;
  return (
    <div onClick={onEdit} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: "grid", gridTemplateColumns: "minmax(220px,2fr) 1.3fr 1fr 1.4fr 40px", gap: 12, padding: "13px 20px", alignItems: "center",
        borderBottom: "1px solid var(--line)", cursor: "pointer", background: hover ? "var(--surface-2)" : "transparent", transition: "background .12s" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
        <Avatar person={p} size={38} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.first} {p.last}</div>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.email}</div>
        </div>
      </div>
      <div style={{ fontSize: 13.5, color: "var(--ink-2)" }}>
        <div style={{ fontWeight: 600 }}>{formatPattern(p.workdays)}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{p.weeklyHours}h / week</div>
      </div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17 }}>
        {p.allowance}<span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 600 }}> days</span>
        {bal.allowance !== p.allowance && (
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", fontWeight: 600, fontFamily: "var(--font-body)" }}>{bal.allowance} this year</div>
        )}
      </div>
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 5 }}>
          <span style={{ color: "var(--ink-3)" }}>{bal.used} used{bal.pending ? ` · ${bal.pending} pending` : ""}</span>
          <span style={{ fontWeight: 700, color: "var(--ink)" }}>{bal.remaining} left</span>
        </div>
        <div style={{ height: 7, borderRadius: 4, background: "var(--paper-2)", overflow: "hidden", display: "flex" }}>
          <div style={{ width: `${usedFrac * 100}%`, background: "var(--accent)" }} />
          <div style={{ width: `${(bal.allowance ? Math.min(bal.pending / bal.allowance, 1 - usedFrac) : 0) * 100}%`, background: "var(--st-pending)", opacity: 0.5 }} />
        </div>
      </div>
      <div style={{ textAlign: "right", color: hover ? "var(--accent)" : "var(--ink-4)" }}><Icon name="chevRight" size={18} /></div>
    </div>
  );
}

Object.assign(window, { TeamAdmin, PersonForm, formatPattern });
