/* Clients — manage client accounts (for agencies & freelance social managers).
   Each client is its own scoped account: brand brief, brand voice, assets, posts
   and campaigns are separate. Assign team members per client and switch the
   active account. Exposed as window.ClientsView. */
(function () {
  const S = window.CroprStore;
  const D = window.CROPR_DATA;

  const fieldStyle = { width: "100%", boxSizing: "border-box", fontFamily: "inherit", fontSize: 13.5, color: "var(--fg1)", background: "var(--surface)", border: "1px solid var(--border-strong)", borderRadius: 10, padding: "9px 11px", outline: "none" };
  const Label = ({ children }) => <span style={{ fontSize: 12, fontWeight: 600, color: "var(--fg2)", display: "block", marginBottom: 6 }}>{children}</span>;
  const dot = (c, size) => <span style={{ width: size, height: size, borderRadius: size * 0.28, flex: "none", background: c.logoUrl ? "var(--bg-muted)" : c.color, color: "#fff", display: "grid", placeItems: "center", fontSize: size * 0.42, fontWeight: 800, overflow: "hidden" }}>{c.logoUrl ? <img src={c.logoUrl} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : (c.name || "?").slice(0, 1).toUpperCase()}</span>;

  function ClientDetail({ id, onBack, onToast, onNav }) {
    const c = S.getClient(id);
    if (!c) return null;
    const team = S.getTeam();
    const stats = S.clientStats(id);
    const active = S.getActiveClientId() === id;
    const switchTo = () => { S.setActiveClient(id); onToast(`Switched to “${c.name}”`); onNav("dashboard"); };
    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
          <Button variant="ghost" icon="arrow-left" onClick={onBack}>Clients</Button>
          <div style={{ flex: 1 }} />
          {active ? <Badge color="#0E8A50" bg="var(--success-bg)" dot>Active account</Badge>
            : <Button variant="primary" icon="log-in" onClick={switchTo}>Switch to this client</Button>}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card pad={20}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 4 }}>
              {dot(c, 46)}
              <div style={{ flex: 1 }}>
                <input defaultValue={c.name} onBlur={(e) => { S.updateClient(id, { name: e.target.value || "Untitled client" }); onToast("Client updated"); }} style={{ ...fieldStyle, fontSize: 17, fontWeight: 700, border: "1px solid transparent", padding: "4px 6px" }} onFocus={(e) => (e.target.style.border = "1px solid var(--border-strong)")} />
              </div>
            </div>
            <div style={{ display: "flex", gap: 18, padding: "10px 6px 0", flexWrap: "wrap" }}>
              {[["posts", "Posts"], ["campaigns", "Campaigns"], ["assets", "Assets"]].map(([k, lbl]) => (
                <div key={k}><span style={{ fontSize: 18, fontWeight: 700, fontFamily: "var(--font-display)" }}>{stats[k]}</span><span style={{ fontSize: 12, color: "var(--fg3)", marginLeft: 6 }}>{lbl}</span></div>
              ))}
            </div>
          </Card>

          <Card pad={20}>
            <SectionTitle icon="building-2">Brand brief</SectionTitle>
            <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 8 }}>Used when the AI generates ideas & posts for this client.</div>
            <textarea defaultValue={c.brandBrief} onBlur={(e) => { S.updateClient(id, { brandBrief: e.target.value }); onToast("Saved"); }} rows={3} placeholder="Who this client is, what they offer, and who they're for." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} />
            <div style={{ height: 14 }} />
            <SectionTitle icon="mic">Brand voice</SectionTitle>
            <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 8 }}>The tone the AI writes this client's posts in.</div>
            <textarea defaultValue={c.brandVoice} onBlur={(e) => { S.updateClient(id, { brandVoice: e.target.value }); onToast("Saved"); }} rows={2} placeholder="e.g. warm and playful, or polished and authoritative." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} />
          </Card>

          <Card pad={20}>
            <SectionTitle icon="users">Who works on this client</SectionTitle>
            <div style={{ fontSize: 12, color: "var(--fg3)", marginBottom: 10 }}>Assign the team members who manage this account.</div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {team.map((m) => {
                const on = (c.users || []).includes(m.id);
                return (
                  <label key={m.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 0", borderBottom: "1px solid var(--border)", cursor: "pointer" }}>
                    {window.memberAvatar(m.name, 30)}
                    <span style={{ flex: 1 }}><span style={{ fontSize: 13.5, fontWeight: 700, display: "block" }}>{m.name}</span><span style={{ fontSize: 11.5, color: "var(--fg3)" }}>{(S.getRoles().find((r) => r.id === m.roleId) || {}).name || m.roleId}</span></span>
                    <button onClick={(e) => { e.preventDefault(); S.assignClientUser(id, m.id, !on); }} style={{ width: 42, height: 24, borderRadius: 999, border: 0, cursor: "pointer", padding: 3, background: on ? "var(--success)" : "var(--border-strong)", display: "flex", justifyContent: on ? "flex-end" : "flex-start", transition: "background 160ms" }}><span style={{ width: 18, height: 18, borderRadius: 999, background: "#fff", boxShadow: "var(--shadow-sm)" }} /></button>
                  </label>
                );
              })}
            </div>
          </Card>

          <Card pad={20}>
            <SectionTitle icon="folder">This client's content</SectionTitle>
            <div style={{ fontSize: 12.5, color: "var(--fg2)", lineHeight: 1.55, marginBottom: 12 }}>Posts, campaigns and assets are kept separate per client. Switch to this account to plan and manage them.</div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <Button variant={active ? "secondary" : "primary"} icon="log-in" onClick={switchTo}>{active ? "Already active" : "Switch & manage"}</Button>
              <Button variant="danger" icon="trash-2" onClick={() => { if (confirm(`Delete client “${c.name}” and all its posts, campaigns and assets?`)) { S.removeClient(id); onToast("Client removed"); onBack(); } }}>Delete client</Button>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  function ClientsView({ onToast, onNav }) {
    const [sel, setSel] = React.useState(null);
    if (sel) return <ClientDetail id={sel} onBack={() => setSel(null)} onToast={onToast} onNav={onNav} />;
    const clients = S.getClients();
    const activeId = S.getActiveClientId();
    const create = () => { const c = S.addClient({ name: "New client" }); onToast("Client created — set up its brand"); setSel(c.id); };
    return (
      <div style={{ maxWidth: "var(--page-w)", margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "center", marginBottom: 18 }}>
          <div style={{ fontSize: 13, color: "var(--fg3)" }}>Each client is a separate account — its own brand, voice, assets, posts and campaigns. Switch accounts from the top of the sidebar.</div>
          <div style={{ flex: 1 }} />
          <Button variant="primary" icon="plus" onClick={create}>New client</Button>
        </div>
        {clients.length === 0 ? (
          <Card pad={44} style={{ textAlign: "center" }}>
            <span style={{ width: 54, height: 54, borderRadius: 15, background: "var(--accent-weak)", display: "inline-grid", placeItems: "center" }}><Icon name="users" size={24} color="var(--accent)" /></span>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 12 }}>No client accounts yet</div>
            <div style={{ fontSize: 13, color: "var(--fg3)", marginTop: 4, marginBottom: 16 }}>Add a client to manage its social presence separately — brand, assets, posts and team.</div>
            <Button variant="primary" icon="plus" onClick={create}>New client</Button>
          </Card>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(280px,1fr))", gap: 16 }}>
            {clients.map((c) => {
              const stats = S.clientStats(c.id);
              const users = (c.users || []).map((uid) => S.getMember(uid)).filter(Boolean);
              const isActive = activeId === c.id;
              return (
                <Card key={c.id} pad={18} onClick={() => setSel(c.id)} hover style={{ cursor: "pointer", border: isActive ? "1.5px solid var(--leap-teal)" : "1px solid var(--border)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 12 }}>
                    {dot(c, 40)}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 15, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--fg3)" }}>{c.brandBrief ? "Brand set" : "No brand yet"} · {c.brandVoice ? "voice set" : "no voice"}</div>
                    </div>
                    {isActive && <Badge color="#0E8A50" bg="var(--success-bg)" dot>Active</Badge>}
                  </div>
                  <div style={{ display: "flex", gap: 14, marginBottom: 12 }}>
                    {[["posts", "Posts"], ["campaigns", "Campaigns"], ["assets", "Assets"]].map(([k, lbl]) => (
                      <div key={k}><span style={{ fontSize: 16, fontWeight: 700, fontFamily: "var(--font-display)" }}>{stats[k]}</span> <span style={{ fontSize: 11, color: "var(--fg3)" }}>{lbl}</span></div>
                    ))}
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <div style={{ display: "flex" }}>{users.slice(0, 5).map((m, i) => <span key={m.id} style={{ marginLeft: i ? -7 : 0, borderRadius: 999, boxShadow: "0 0 0 2px var(--surface)" }}>{window.memberAvatar(m.name, 24)}</span>)}</div>
                    {!users.length && <span style={{ fontSize: 11.5, color: "var(--fg4)" }}>No one assigned</span>}
                    <div style={{ flex: 1 }} />
                    <button onClick={(e) => { e.stopPropagation(); S.setActiveClient(c.id); onToast(`Switched to “${c.name}”`); onNav("dashboard"); }} style={{ border: "1px solid var(--border-strong)", background: "var(--surface)", borderRadius: 999, padding: "5px 11px", cursor: "pointer", fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "var(--accent)" }}>Switch</button>
                  </div>
                </Card>
              );
            })}
          </div>
        )}
      </div>
    );
  }
  window.ClientsView = ClientsView;
})();
