/* ===========================================================================
   launch-hubs-c.jsx — Workspace + Settings hubs.
   =========================================================================== */
const { LccPage: LccPageC, LccTabs: LccTabsC, LCC_TABS: TABS_C, Section: SectionC, Avatar: AvatarC, Bar: BarC, ENGINE_COLORS: EC } = window;

/* ---------------------------------------------------------------------------
   WORKSPACE — Team · Checklists · Files · Timeline.
   --------------------------------------------------------------------------- */
function TeamRoster() {
  const [team, setTeam] = window.useDB("launchTeam");
  const [tasks] = window.useDB("launchTasks");
  const openFor = (m) => tasks.filter((t) => t.owner === (m.name || "").split(" ")[0] && t.status !== "done").length;
  const loadTone = { high: "#F25BA7", med: "#E0B638", low: "#10B5C7" };
  const PALETTE = ["#C49800", "#B5006A", "#007A8A", "#4C1285", "#00A8BC", "#D8288C", "#7A4FBF"];
  const [edit, setEdit] = React.useState(null);
  const save = () => { setTeam((xs) => edit.isNew ? [...xs, { ...edit }] : xs.map((m) => m.id === edit.id ? { ...edit } : m)); if (window.argtPing) window.argtPing(edit.name + " saved"); setEdit(null); };
  const del = (id) => { setTeam((xs) => xs.filter((m) => m.id !== id)); setEdit(null); };
  const add = () => setEdit({ id: Date.now(), name: "", role: "", load: "med", color: PALETTE[team.length % PALETTE.length], isNew: true });
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <span className="micro">{team.length} TEAMMATES · TAP TO EDIT</span>
        <button className="pill active" onClick={add}>Add teammate</button>
      </div>
      <div className="grid-cols-3">
        {team.map((m) => (
          <div key={m.id} className="card" onClick={() => setEdit({ ...m })} title="Tap to edit" style={{ display: "flex", flexDirection: "column", gap: 12, cursor: "pointer" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <AvatarC name={m.name} color={m.color} size={42} />
              <div><div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15 }}>{m.name}</div><div style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{m.role}</div></div>
            </div>
            <div className="stat-rows">
              <div className="stat-row"><span className="lab">Open tasks</span><span className="num">{openFor(m)}</span></div>
              <div className="stat-row"><span className="lab">Workload</span><span style={{ fontSize: 11, fontWeight: 800, textTransform: "uppercase", color: loadTone[m.load] }}>{m.load}</span></div>
            </div>
          </div>
        ))}
      </div>
      <LccModal open={!!edit} title={edit && edit.isNew ? "Add teammate" : "Edit teammate"} onClose={() => setEdit(null)} onSubmit={save} submitLabel={edit && edit.isNew ? "Add" : "Save"}>
        {edit && (<>
          <LccField label="Name"><input style={lccInput()} placeholder="Full name" value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} /></LccField>
          <LccField label="Role"><input style={lccInput()} placeholder="e.g. Production Manager" value={edit.role} onChange={(e) => setEdit({ ...edit, role: e.target.value })} /></LccField>
          <LccField label="Workload"><select style={lccInput()} value={edit.load} onChange={(e) => setEdit({ ...edit, load: e.target.value })}><option value="low">Low</option><option value="med">Medium</option><option value="high">High</option></select></LccField>
          <LccField label="Avatar color">
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {PALETTE.map((col) => <button key={col} onClick={() => setEdit({ ...edit, color: col })} style={{ width: 28, height: 28, borderRadius: "50%", background: col, border: edit.color === col ? "2px solid var(--pvt-text)" : "2px solid transparent", cursor: "pointer" }} />)}
            </div>
          </LccField>
          {!edit.isNew && <button className="pill" onClick={() => del(edit.id)} style={{ alignSelf: "flex-start", color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Remove teammate</button>}
        </>)}
      </LccModal>
    </div>
  );
}

function Checklists() {
  const team = window.ARGT_DB.get("launchTeam") || [];
  const [items, setItems] = window.useDB("checklists");
  const [edit, setEdit] = React.useState(null);
  const done = items.filter((i) => i.done).length;
  const toggle = (id) => setItems((xs) => xs.map((x) => x.id === id ? { ...x, done: !x.done } : x));
  const move = (i, dir) => setItems((xs) => { const j = i + dir; if (j < 0 || j >= xs.length) return xs; const c = xs.slice(); const t = c[i]; c[i] = c[j]; c[j] = t; return c; });
  const remove = (id) => setItems((xs) => xs.filter((x) => x.id !== id));
  const saveEdit = () => { setItems((xs) => xs.map((x) => x.id === edit.id ? { ...edit } : x)); if (window.argtPing) window.argtPing("Checklist item updated"); setEdit(null); };
  const mvBtn = { width: 22, height: 16, display: "grid", placeItems: "center", background: "var(--pvt-surface-light)", border: "1px solid var(--pvt-border-light)", borderRadius: 5, color: "var(--pvt-text-dim)", fontSize: 8, cursor: "pointer", padding: 0, fontFamily: "var(--pvt-font-body)" };
  return (
    <SectionC title="Launch checklists" action={<span className="micro">{done}/{items.length} DONE</span>}>
      <div className="stat-rows">
        {items.map((it, i) => (
          <div key={it.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto auto", gap: 14, alignItems: "center", opacity: it.done ? 0.6 : 1 }}>
            <span onClick={() => toggle(it.id)} title="Toggle done" style={{ width: 22, height: 22, borderRadius: 7, border: "2px solid " + (it.done ? "var(--role-accent)" : "var(--pvt-border-light)"), background: it.done ? "var(--role-accent)" : "transparent", display: "grid", placeItems: "center", color: "#fff", fontSize: 13, fontWeight: 800, cursor: "pointer", flexShrink: 0 }}>{it.done ? "✓" : ""}</span>
            <span onClick={() => setEdit({ ...it })} title="Click to edit" style={{ fontSize: 13.5, textDecoration: it.done ? "line-through" : "none", cursor: "pointer" }}>{it.label}</span>
            <span style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{it.cadence}</span>
            <span style={{ fontSize: 12, color: "var(--pvt-text-dim)", display: "flex", gap: 8, alignItems: "center" }}><span>{it.due}</span><span style={{ fontFamily: "var(--pvt-font-display)" }}>{it.owner}</span></span>
            <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ display: "inline-flex", flexDirection: "column", gap: 2 }}>
                <button title="Move up" disabled={i === 0} onClick={() => move(i, -1)} style={{ ...mvBtn, opacity: i === 0 ? 0.3 : 1, cursor: i === 0 ? "default" : "pointer" }}>▲</button>
                <button title="Move down" disabled={i === items.length - 1} onClick={() => move(i, 1)} style={{ ...mvBtn, opacity: i === items.length - 1 ? 0.3 : 1, cursor: i === items.length - 1 ? "default" : "pointer" }}>▼</button>
              </span>
              <button title="Delete item" onClick={() => remove(it.id)} style={{ width: 26, height: 26, borderRadius: 7, display: "grid", placeItems: "center", background: "var(--pvt-surface-light)", border: "1px solid var(--pvt-border-light)", color: "var(--pvt-text-dim)", cursor: "pointer", fontSize: 15, lineHeight: 1 }}>×</button>
            </span>
          </div>
        ))}
      </div>
      <LccModal open={!!edit} title="Edit checklist item" onClose={() => setEdit(null)} onSubmit={saveEdit} submitLabel="Save">
        {edit && (<>
          <LccField label="Item"><input style={lccInput()} value={edit.label} onChange={(e) => setEdit({ ...edit, label: e.target.value })} /></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <LccField label="Owner"><select style={lccInput()} value={edit.owner} onChange={(e) => setEdit({ ...edit, owner: e.target.value })}>{team.map((m) => <option key={m.id} value={m.name.split(" ")[0]}>{m.name.split(" ")[0]}</option>)}</select></LccField>
            <LccField label="Cadence"><select style={lccInput()} value={edit.cadence} onChange={(e) => setEdit({ ...edit, cadence: e.target.value })}><option>once</option><option>weekly</option><option>daily</option></select></LccField>
            <LccField label="Due"><input style={lccInput()} value={edit.due} onChange={(e) => setEdit({ ...edit, due: e.target.value })} /></LccField>
          </div>
        </>)}
      </LccModal>
    </SectionC>
  );
}

function Files() {
  const [files, setFiles] = window.useDB("launchFiles");
  const fmt = (b) => b >= 1e6 ? (b / 1e6).toFixed(1) + " MB" : (b / 1e3).toFixed(0) + " KB";
  const [edit, setEdit] = React.useState(null);
  const save = () => { setFiles((xs) => xs.map((f) => f.id === edit.id ? { ...f, name: edit.name } : f)); if (window.argtPing) window.argtPing("Renamed to " + edit.name); setEdit(null); };
  const del = (id) => { setFiles((xs) => xs.filter((f) => f.id !== id)); setEdit(null); };
  const addFolder = () => setFiles((xs) => [{ id: "f" + Date.now(), type: "folder", name: "New folder", parentId: null, items: 0, sizeBytes: 0, updatedAt: "now" }, ...xs]);
  return (
    <SectionC title="Shared files" action={<span style={{ display: "flex", gap: 8 }}><button className="pill" onClick={addFolder}>New folder</button><button className="pill active" onClick={() => window.argtPing && window.argtPing("Upload starts in the fold")}>Upload</button></span>}>
      <div className="grid-cols-3">
        {files.map((f) => (
          <div key={f.id} className="tile" onClick={() => setEdit({ ...f })} title="Tap to open" style={{ minHeight: 120, cursor: "pointer" }}>
            <div className="ico">{f.type === "folder" ? "▣" : (f.mime || "·").toUpperCase().slice(0, 3)}</div>
            <div className="name" style={{ fontSize: 14 }}>{f.name}</div>
            <div className="desc">{f.type === "folder" ? f.items + " items" : fmt(f.sizeBytes)} · {f.updatedAt}</div>
          </div>
        ))}
      </div>
      <LccModal open={!!edit} title={edit && edit.type === "folder" ? "Folder" : "File"} onClose={() => setEdit(null)} onSubmit={save} submitLabel="Save">
        {edit && (<>
          <LccField label="Name"><input style={lccInput()} value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} /></LccField>
          <div style={{ fontSize: 12.5, color: "var(--pvt-text-dim)" }}>{edit.type === "folder" ? edit.items + " items" : fmt(edit.sizeBytes)} · updated {edit.updatedAt}</div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <button className="pill" onClick={() => window.argtPing && window.argtPing(edit.type === "folder" ? "Opening folder…" : "Downloading " + edit.name)}>{edit.type === "folder" ? "Open" : "Download"}</button>
            <button className="pill" onClick={() => del(edit.id)} style={{ color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Delete</button>
          </div>
        </>)}
      </LccModal>
    </SectionC>
  );
}

function Timeline() {
  const [weeks] = window.useDB("timeline");
  const tw = (window.ARGT_DB.get("launchSettings") || {}).timelineWeeks || 20;
  const tone = { doing: "#10B5C7", todo: "var(--pvt-text-dim)", done: "#D8288C" };
  const span = weeks.length ? weeks[0].week + " → " + weeks[weeks.length - 1].week : "—";
  return (
    <SectionC title={tw + "-week production timeline"} action={<span className="micro">{span} · EDIT IN SETTINGS</span>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {weeks.map((w, i, arr) => (
          <div key={w.week} style={{ display: "grid", gridTemplateColumns: "70px 1fr", gap: 16, position: "relative", paddingBottom: i < arr.length - 1 ? 18 : 0 }}>
            <div style={{ textAlign: "right", fontFamily: "var(--pvt-font-display)", fontSize: 13, color: "var(--role-accent-bright)", paddingTop: 2 }}>{w.week}</div>
            <div style={{ position: "relative", paddingLeft: 22 }}>
              <span style={{ position: "absolute", left: 0, top: 4, width: 14, height: 14, borderRadius: "50%", background: tone[w.status], boxShadow: "0 0 0 4px var(--pvt-surface)", zIndex: 2 }} />
              {i < arr.length - 1 && <span style={{ position: "absolute", left: 6, top: 16, bottom: -18, width: 2, background: "var(--pvt-surface-light)" }} />}
              <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 14.5 }}>{w.label}</div>
              <div style={{ display: "flex", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
                {w.milestones.map((m, j) => <span key={j} style={{ fontSize: 11.5, color: "var(--pvt-muted)", background: "var(--pvt-surface-mid)", padding: "4px 10px", borderRadius: 99 }}>{m}</span>)}
                <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--pvt-text-dim)" }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: EC[w.engine] }} />{w.engine}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </SectionC>
  );
}

function WorkspaceHub({ tab, go }) {
  const [, setItems] = window.useDB("checklists");
  const team = window.ARGT_DB.get("launchTeam") || [];
  const [showAdd, setShowAdd] = React.useState(false);
  const [d, setD] = React.useState({ label: "", owner: "Kam", due: "" });
  const add = () => {
    if (!d.label.trim()) return;
    setItems((xs) => [...xs, { id: "ch" + Date.now(), label: d.label.trim(), owner: d.owner, due: d.due || "TBD", cadence: "once", done: false }]);
    if (window.argtPing) window.argtPing("Checklist item added");
    setShowAdd(false); setD({ label: "", owner: "Kam", due: "" });
  };
  return (
    <LccPageC eyebrow="WORKSPACE" title="Workspace"
      lede="The shared operating layer: who is on the team and how loaded they are, the templated launch checklists, the file workspace, and the full production timeline from now to gates."
      actions={<button className="pill active" onClick={() => setShowAdd(true)}>New checklist</button>}>
      <LccTabsC tabs={TABS_C.workspace} active={tab} onChange={(t) => go("workspace", t)} />
      {tab === "team" && <TeamRoster />}
      {tab === "checklists" && <Checklists />}
      {tab === "files" && <Files />}
      {tab === "timeline" && <Timeline />}
      <LccModal open={showAdd} title="New checklist item" onClose={() => setShowAdd(false)} onSubmit={add} submitLabel="Add item">
        <LccField label="Item"><input style={lccInput()} placeholder="What needs to be done?" value={d.label} onChange={(e) => setD({ ...d, label: e.target.value })} /></LccField>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <LccField label="Owner"><select style={lccInput()} value={d.owner} onChange={(e) => setD({ ...d, owner: e.target.value })}>{team.map((m) => <option key={m.id} value={m.name.split(" ")[0]}>{m.name.split(" ")[0]}</option>)}</select></LccField>
          <LccField label="Due"><input style={lccInput()} placeholder="Jun 20" value={d.due} onChange={(e) => setD({ ...d, due: e.target.value })} /></LccField>
        </div>
      </LccModal>
    </LccPageC>
  );
}

/* ---------------------------------------------------------------------------
   SETTINGS — Festival · Integrations · Notifications · Roles · Storage.
   --------------------------------------------------------------------------- */
function inputStyleC() {
  return { background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", color: "var(--pvt-text)", padding: "12px 14px", fontSize: 13, fontFamily: "var(--pvt-font-body)", outline: "none", width: "100%" };
}
function Field({ label, value }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <label style={{ fontSize: 11, color: "var(--pvt-text-dim)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 700 }}>{label}</label>
      <input style={inputStyleC()} defaultValue={value} />
    </div>
  );
}
/* Superseded by launch-settings.jsx (LccSettings). Kept dormant; not registered. */
function SettingsHubLegacyUnused({ tab, go }) {
  const s = window.ARGT_DB.get("launchSettings");
  const [notifs, setNotifs] = window.useDB("launchSettings");
  const [access, setAccess] = window.useDB("launchAccess");
  const toggleN = (k) => setNotifs((x) => ({ ...x, notifications: { ...x.notifications, [k]: !x.notifications[k] } }));
  const [invEmail, setInvEmail] = React.useState("");
  const [invRole, setInvRole] = React.useState("Editor");
  const sendInvite = () => {
    if (!invEmail.trim()) return;
    setAccess((a) => ({ ...a, invites: [...(a.invites || []), { id: "inv" + Date.now(), email: invEmail.trim(), role: invRole, status: "pending", sent: "now" }] }));
    if (window.argtPing) window.argtPing("Invite sent to " + invEmail.trim());
    setInvEmail("");
  };
  const setPersonAccess = (id, val) => setNotifs((x) => ({ ...x, roles: x.roles.map((r) => r.id === id ? { ...r, access: val } : r) }));
  return (
    <LccPageC eyebrow="SETTINGS" title="Configuration"
      lede="Festival profile, connected services, alerting, who can touch what, and storage. The control surface behind the command center."
      actions={<button className="pill active">Save changes</button>}>
      <LccTabsC tabs={TABS_C.settings} active={tab} onChange={(t) => go("settings", t)} />

      {tab === "festival" && (
        <SectionC title="Festival profile">
          <div className="grid-form-2">
            <Field label="Festival name" value={s.festival.name} />
            <Field label="Dates" value={s.festival.dates} />
            <div style={{ gridColumn: "1 / -1" }}><Field label="Venue" value={s.festival.venue} /></div>
            <Field label="Capacity" value={s.festival.capacity} />
            <Field label="Stages" value={String(s.festival.stages)} />
            <Field label="Artists" value={s.festival.artists} />
            <Field label="Beneficiary" value="Clean Earth Initiative · 10% of every ticket" />
          </div>
        </SectionC>
      )}

      {tab === "integrations" && (
        <SectionC title="Connected services">
          <div className="stat-rows">
            {s.integrations.map((ig) => (
              <div key={ig.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 14, alignItems: "center" }}>
                <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13.5 }}>{ig.name}</span>
                <span style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{ig.purpose}</span>
                <Badge kind={ig.status === "connected" ? "approved" : "pending"}>{ig.status === "connected" ? "Connected" : "Action needed"}</Badge>
              </div>
            ))}
          </div>
        </SectionC>
      )}

      {tab === "notifications" && (
        <SectionC title="Alerting">
          <div className="stat-rows">
            {Object.entries(s.notifications).map(([k, v]) => (
              <div key={k} className="stat-row" style={{ cursor: "pointer" }} onClick={() => toggleN(k)}>
                <span className="lab">{k}</span>
                <span className="pill" style={{ background: v ? "var(--role-accent)" : "transparent", color: v ? "#fff" : "var(--pvt-muted)", borderColor: v ? "var(--role-accent)" : "var(--pvt-border-light)" }}>{v ? "On" : "Off"}</span>
              </div>
            ))}
          </div>
        </SectionC>
      )}

      {tab === "roles" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <SectionC title="Invite to the command center">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 160px auto", gap: 10, alignItems: "center" }}>
              <input style={inputStyleC()} placeholder="name@argt.com" value={invEmail} onChange={(e) => setInvEmail(e.target.value)} />
              <select style={inputStyleC()} value={invRole} onChange={(e) => setInvRole(e.target.value)}>
                <option>Admin</option><option>Editor</option><option>Viewer</option>
              </select>
              <button className="pill active" onClick={sendInvite}>Send invite</button>
            </div>
            <p style={{ fontSize: 11.5, color: "var(--pvt-text-dim)", margin: "12px 0 0", lineHeight: 1.5 }}>Admins can open Settings and edit the festival profile. Editors work the operational hubs. Viewers are read-only. Only Owner and Admin can reach this configuration surface.</p>
          </SectionC>

          <SectionC title="Team & access">
            <div className="stat-rows">
              {s.roles.map((r) => (
                <div key={r.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "auto 1fr 1fr 130px", gap: 14, alignItems: "center" }}>
                  <AvatarC name={r.name} size={28} />
                  <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13.5 }}>{r.name}</span>
                  <span style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{r.scope}</span>
                  {r.access === "Owner" ? (
                    <Badge kind="approved">Owner</Badge>
                  ) : (
                    <select style={{ ...inputStyleC(), padding: "7px 10px", fontSize: 12 }} value={r.access} onChange={(e) => setPersonAccess(r.id, e.target.value)}>
                      <option>Admin</option><option>Editor</option><option>Viewer</option>
                    </select>
                  )}
                </div>
              ))}
            </div>
          </SectionC>

          {(access.invites || []).length > 0 && (
            <SectionC title="Pending invites" action={<span className="micro">{access.invites.length} OUTSTANDING</span>}>
              <div className="stat-rows">
                {access.invites.map((iv) => (
                  <div key={iv.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr auto auto auto", gap: 14, alignItems: "center" }}>
                    <span style={{ fontSize: 13 }}>{iv.email}</span>
                    <Badge kind="review">{iv.role}</Badge>
                    <span style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>sent {iv.sent}</span>
                    <Badge kind="pending">Pending</Badge>
                  </div>
                ))}
              </div>
            </SectionC>
          )}
        </div>
      )}

      {tab === "storage" && (
        <SectionC title="Storage">
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}><span style={{ color: "var(--pvt-muted)" }}>Used</span><span style={{ fontFamily: "var(--pvt-font-display)" }}>{s.storage.usedGb} GB of {s.storage.totalGb} GB</span></div>
            <BarC pct={s.storage.usedGb / s.storage.totalGb * 100} />
            <p style={{ fontSize: 12.5, color: "var(--pvt-text-dim)", margin: 0 }}>Media library, contracts, stage plots, and creative. Upgrade adds 200 GB blocks.</p>
          </div>
        </SectionC>
      )}
    </LccPageC>
  );
}

window.LCC_PAGES = Object.assign(window.LCC_PAGES || {}, {
  workspace: (tab, go) => <WorkspaceHub tab={tab} go={go} />,
});
