// Goals admin screen — set per-role weekly goals + per-sub-team overrides.
// Admin only.

function GoalsScreen() {
  const G = window.VAULT_GOALS;
  const F = window.VAULT_FIRM;
  const [goals, setGoals] = React.useState(() => G.load());
  const [tab, setTab] = React.useState("base"); // base | overrides
  const [overrideSubteam, setOverrideSubteam] = React.useState(null);
  const [dirty, setDirty] = React.useState(false);

  const updateBase = (role, metric, value) => {
    setGoals(g => {
      const next = JSON.parse(JSON.stringify(g));
      next.base[role][metric] = value === "" ? 0 : Number(value);
      return next;
    });
    setDirty(true);
  };

  const updateOverride = (subteamId, role, metric, value) => {
    setGoals(g => {
      const next = JSON.parse(JSON.stringify(g));
      if (!next.overrides[subteamId]) next.overrides[subteamId] = {};
      if (!next.overrides[subteamId][role]) next.overrides[subteamId][role] = {};
      if (value === "" || value == null) {
        delete next.overrides[subteamId][role][metric];
        if (Object.keys(next.overrides[subteamId][role]).length === 0) delete next.overrides[subteamId][role];
        if (Object.keys(next.overrides[subteamId]).length === 0) delete next.overrides[subteamId];
      } else {
        next.overrides[subteamId][role][metric] = Number(value);
      }
      return next;
    });
    setDirty(true);
  };

  const saveAll = () => { G.save(goals); G.notify(); setDirty(false); };
  const discard = () => { setGoals(G.load()); setDirty(false); };
  const resetAll = () => {
    if (!confirm("Reset ALL weekly goals to factory defaults? Per-team overrides will be cleared.")) return;
    G.reset();
    setGoals(G.load());
    G.notify();
    setDirty(false);
  };

  const subteamsForOverride = F.SUBTEAMS.filter(s => s.moduleId === "deals");

  return (
    <div style={{ padding: "20px 28px 60px" }}>
      <div className="row" style={{ marginBottom: 16, alignItems: "flex-end" }}>
        <div className="stretch">
          <div className="display" style={{ fontSize: 22, fontWeight: 400, letterSpacing: "-.01em" }}>Weekly Goals</div>
          <div className="muted small" style={{ marginTop: 2 }}>
            Targets are per-person per-week. Overview compares scoped activity to <span className="mono">sum(people × weeks × goal)</span> and color-codes
            <span className="pill ok" style={{ marginLeft: 6 }}><span className="dot"/>≥81%</span>
            <span className="pill warn" style={{ marginLeft: 4 }}><span className="dot"/>60–80%</span>
            <span className="pill danger" style={{ marginLeft: 4 }}><span className="dot"/>&lt;60%</span>
          </div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          {dirty && <span className="muted small mono" style={{ color: "var(--warn, #c08a1e)" }}>unsaved changes</span>}
          <button className="btn ghost sm" onClick={resetAll}>Reset defaults</button>
          {dirty && <button className="btn ghost sm" onClick={discard}>Discard</button>}
          <button className="btn primary sm" disabled={!dirty} onClick={saveAll}>Save goals</button>
        </div>
      </div>

      <div className="row" style={{ borderBottom: "1px solid var(--line-2)", marginBottom: 14, gap: 4 }}>
        <TabBtn id="base"      label="Firm-wide by role"  active={tab==="base"}      onClick={() => setTab("base")}/>
        <TabBtn id="overrides" label="Per-team overrides" active={tab==="overrides"} onClick={() => setTab("overrides")}/>
      </div>

      {tab === "base" && (
        <div className="card" style={{ overflow: "hidden" }}>
          <table className="dt" style={{ fontSize: 12.5 }}>
            <thead>
              <tr>
                <th style={{ minWidth: 110 }}>Role</th>
                {G.METRICS.map(m => <th key={m} className="r" style={{ minWidth: 90 }}>{G.METRIC_LABELS[m]}</th>)}
              </tr>
            </thead>
            <tbody>
              {G.ROLES.map(role => (
                <tr key={role}>
                  <td style={{ fontWeight: 600 }}>{role}</td>
                  {G.METRICS.map(m => (
                    <td key={m} className="r">
                      <input type="number" step="0.05" min="0" className="input" style={{ width: 80, textAlign: "right", fontFamily: "var(--f-mono)" }}
                        value={goals.base[role][m] ?? 0}
                        onChange={e => updateBase(role, m, e.target.value)}/>
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
          <div className="muted small" style={{ padding: "10px 14px", borderTop: "1px solid var(--line-2)" }}>
            Values are weekly per person. Decimals are fine (e.g. 0.15 signed LOIs/wk ≈ 1 every 7 weeks).
          </div>
        </div>
      )}

      {tab === "overrides" && (
        <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 14 }}>
          <div className="card" style={{ padding: 8, maxHeight: 520, overflowY: "auto" }}>
            <div className="micro" style={{ padding: "4px 8px" }}>Deal-team sub-teams</div>
            {subteamsForOverride.map(s => {
              const has = !!goals.overrides[s.id];
              const on = overrideSubteam === s.id;
              return (
                <button key={s.id} onClick={() => setOverrideSubteam(s.id)} style={{
                  display: "flex", width: "100%", alignItems: "center", gap: 8,
                  padding: "8px 10px", border: "none",
                  background: on ? "var(--accent-soft)" : "transparent",
                  color: on ? "var(--accent)" : "var(--ink)",
                  borderRadius: 6, cursor: "pointer", textAlign: "left", fontSize: 12.5,
                  fontWeight: on ? 600 : 400,
                }}>
                  <span className="stretch">{s.label}</span>
                  {has && <span className="mono small" style={{ color: "var(--accent)" }}>●</span>}
                </button>
              );
            })}
          </div>
          <div className="card" style={{ overflow: "hidden" }}>
            {!overrideSubteam && (
              <div className="muted" style={{ padding: 40, textAlign: "center" }}>
                Pick a sub-team to set per-role overrides. Empty cells inherit the firm-wide base goal.
              </div>
            )}
            {overrideSubteam && (() => {
              const s = F.SUBTEAMS.find(x => x.id === overrideSubteam);
              const ov = goals.overrides[overrideSubteam] || {};
              return (
                <>
                  <div className="row" style={{ padding: "12px 16px", borderBottom: "1px solid var(--line-2)" }}>
                    <div className="display" style={{ fontSize: 16, fontWeight: 400 }}>{s.label} <span className="muted small">— per-role overrides</span></div>
                    <button className="btn ghost sm" style={{ marginLeft: "auto" }} onClick={() => {
                      setGoals(g => { const next = JSON.parse(JSON.stringify(g)); delete next.overrides[overrideSubteam]; return next; });
                      setDirty(true);
                    }}>Clear all</button>
                  </div>
                  <table className="dt" style={{ fontSize: 12.5 }}>
                    <thead>
                      <tr>
                        <th style={{ minWidth: 100 }}>Role</th>
                        {G.METRICS.map(m => <th key={m} className="r" style={{ minWidth: 90 }}>{G.METRIC_LABELS[m]}</th>)}
                      </tr>
                    </thead>
                    <tbody>
                      {G.ROLES.map(role => (
                        <tr key={role}>
                          <td style={{ fontWeight: 600 }}>{role}</td>
                          {G.METRICS.map(m => {
                            const base = goals.base[role][m];
                            const v = ov[role]?.[m];
                            const isOverridden = v != null;
                            return (
                              <td key={m} className="r">
                                <input type="number" step="0.05" min="0" placeholder={String(base)} className="input"
                                  style={{
                                    width: 80, textAlign: "right", fontFamily: "var(--f-mono)",
                                    background: isOverridden ? "var(--accent-soft)" : undefined,
                                    borderColor: isOverridden ? "var(--accent)" : undefined,
                                  }}
                                  value={isOverridden ? v : ""}
                                  onChange={e => updateOverride(overrideSubteam, role, m, e.target.value)}/>
                              </td>
                            );
                          })}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  <div className="muted small" style={{ padding: "10px 14px", borderTop: "1px solid var(--line-2)" }}>
                    Leave a cell blank to inherit the firm-wide base goal (shown as placeholder).
                  </div>
                </>
              );
            })()}
          </div>
        </div>
      )}
    </div>
  );
}

function TabBtn({ id, label, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      background: "transparent", border: "none",
      padding: "10px 14px", cursor: "pointer",
      fontFamily: "var(--f-display)", fontSize: 14, fontWeight: 400,
      color: active ? "var(--ink)" : "var(--muted)",
      borderBottom: active ? "2px solid var(--accent)" : "2px solid transparent",
    }}>{label}</button>
  );
}

window.GoalsScreen = GoalsScreen;
